ラベル android の投稿を表示しています。 すべての投稿を表示
ラベル android の投稿を表示しています。 すべての投稿を表示

2016年5月22日日曜日

AndroidでFirebase Analyticsを使う


(引用元:https://firebase.google.com)

セットアップ

セットアップ方法は、必ず最新の情報を参照ください。
公式Page
https://firebase.google.com/docs/android/setup

プロジェクトのbuild.gradleに次のclasspathを追加する。
buildscript {
  dependencies {
    classpath 'com.google.gms:google-services:3.0.0'
  }
}


appのbuild.gradleに次のpluginを追加する。

// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

Firebase Analyticsを使用するには、次のdependenciesを追加する。
dependencies {
    compile 'com.google.firebase:firebase-analytics:9.0.0'
}

Analytics以外の機能を使用するには、次の公式サイトに記載されているdependenciesを追加しましょう。
https://firebase.google.com/docs/android/setup#available_libraries

イベントの送信

イベントの種類
以下、宣言済みのイベントがあります。
https://support.google.com/firebase/answer/6317485?hl=en&ref_topic=6317484
FirebaseAnalytics.Event
https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event

  • Automatically collected events
  • Events: All apps
  • Events: Retail/Ecommerce
  • Events: Jobs, Education, Local Deals, Real Estate
  • Events: Travel (Hotel/Air)
  • Events: Games
  • Automatically collected user properties



宣言済みのイベント以外にも、オリジナルのイベントの追加が可能ですが以下の制限があります。

  • イベントは500種類まで
  • イベント名はユニークな名前であること
  • イベント名のPrefixに"firebase_"を付けない(SHOULD)
  • イベント名は32文字の、アルファベットとunderscores( _ )のみ


パラメータ
各イベントに25個までのパラメータを付加することが可能です。定義済みのパラメータがあります。
FirebaseAnalytics.Param
https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Param

イベント同様、オリジナルのパラメータの追加が可能です。
  • パラメータ名は24文字の、アルファベットとunderscores( _ )のみ
  • パラメータの値は36文字まで
  • Prefixに"firebase_"を付けない(SHOULD)


イベントの送信方法
Bundleにパラメータを詰めて、logEventにイベント名とBundleを渡すだけ送信可能です。

FirebaseAnalytics mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, id);
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);


ユーザープロパティ

アプリのユーザーをカテゴライズすることが可能です。
FirebaseAnalytics.UserProperty
https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.UserProperty

アプリごとに25種類までユーザー属性を追加することができます。

  • ユーザープロパティ名は24文字まで、アルファベットとunderscores( _ )のみ
  • ユーザープロパティの値は36文字まで
  • Prefixに"firebase_"を付けない(SHOULD)


FirebaseAnalytics mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
mFirebaseAnalytics.setUserProperty("favorite_food", mFavoriteFood);

2016年3月5日土曜日

BottomSheetの実装方法 via Android Design Support Library 23.2

Android Design Support Library 23.2でBottomSheetが追加されました。
GoogleMapなどに用いられている画面が作成可能になりました。
実装はCoordinatorLayoutの子Viewに対して、Behaviorを指定するだけとシンプルです。

AOSPのソースコード : BottomSheetBehavior.java

Layoutのサンプル

BottomSheetはBehaviorを指定することで実装します。
CoordinatorLayoutの子ViewとしてLayoutを追加して、BottomSheet化したいLayoutに対してapp:layout_behavior="@string/bottom_sheet_behavior"を指定します。

<android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            app:layout_behavior="@string/bottom_sheet_behavior"
            app:behavior_peekHeight="240dp"
            app:behavior_hideable="false"
            android:background="@android:color/white">
        <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="BottomSheet Sample"/>
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

次のパラメータの指定が可能です。

  • app:behavior_peekHeight
    • BottomSheetの最小表示サイズ
  • app:behavior_hideable
    • 下スクロールで完全に非表示にするかどうか。非表示後に上スクロールで表示可能


2016年2月13日土曜日

Android M Fingerprint APIについて調べてみた

関西モバイル研究会で発表した内容です。

Android M FingerPrint(public)
http://www.slideshare.net/baroqueworksdev/android-m-finger-printpublic

簡易クラス図

アプリからHAL層までの簡易クラス図です。



アプリケーションから使用する場合

  • Context#getSystemService()でFragmentprintManagerにアクセス 
  • コールバックで結果を受け取る

FingerprintManagerクラス

  • アプリケーションから要求を受け取る
  • Android Frameworksのサービス群にある、FingerprintServiceに連携
  • 認証結果をFingerprintServiceから受け取り、アプリケーションに通知する

FingerprintServiceクラス

  • SystemServiceクラスを継承
  • Android Systemとして指紋認証機能を実行
  • Native(JNI->HAL)につなぐ
  • 認証要求時にFingerprintDeamonクラスをとおして、Native層に通知 アプリケーションの突然死の際、unbindする(IBinder.DeathRecipient)

JNI / HAL層

  • HAL層(ライブラリ)をとおして、Kernelに通知、ハードウェアの制御を行う
  • 認証結果をKeystoreServiceに通知

2015年10月7日水曜日

[Nexus5][Android 6.0]OTAを手動でUpdateする

Android 6.0のOTA配信が始まりました。
XDAでOTA URLが投稿されています。

http://forum.xda-developers.com/google-nexus-5/general/ref-nexus-5-stock-ota-urls-t2475327

と、いうことでadbコマンドを使用して手動でUpdateしました。


curl -L https://android.googleapis.com/packages/ota/google_hammerhead/8f8cc12f7a9d7561be21f95914f289bda86e402b.signed-hammerhead-MRA58K-from-LMY48M.zip > 8f8cc12f7a9d7561be21f95914f289bda86e402b.signed-hammerhead-MRA58K-from-LMY48M.zip
adb reboot bootloader 
adb sideload 8f8cc12f7a9d7561be21f95914f289bda86e402b.signed-hammerhead-MRA58K-from-LMY48M.zip


2015年9月16日水曜日

Android Mリリース目前のAOSP mirrorの容量



久々にAOSP mirrorを作ってみました。
(備考:ローカルにAOSPのミラーを作成)


容量80GB超えたよ

上記の画像を見ていただければ、お分かり頂けると思いますが、容量が81.25GBと良い勢いで増えています。
いまSSD 128GB上に作成していますが、Android Mがリリースされると100GBまで行くんじゃないかと心配です。



とはいえ、頻繁にAOSPのソースを取得する現場ですと、mirrorがある方が効率的ですので導入を推奨いたします。

2015年9月15日火曜日

AOSP mirrorのrepo syncエラー: GPGが更新されない

久々にAOSP mirrorのrepo syncを実行したところ、エラーとなりました。
どうも、repoの更新ができていないよう。

info: A new version of repo is available


object 5ea32d135963da5542b78895f95332c6a17bbe11
type commit
tag v1.12.31
tagger Dan Willemsen  1441912006 -0700

repo v1.12.31

error: cannot run gpg: No such file or directory
error: could not run gpg.
error: could not verify the tag 'v1.12.31'


warning: Skipped upgrade to unverified version

ググってみたところ、次の方法で解決できるとのこと。
https://groups.google.com/forum/#!searchin/android-building/repo/android-building/ICajKIQlwC8/hxKulJLZ278J

mv ~/.repoconfig/gnupg ~/.repoconfig/gnupg_OLD

repoのconfig内のgnupgが更新されていないようなので、新規で取ってこいってことかな???
mv実行後、repo syncは無事に完遂しました。

2015年6月13日土曜日

CoordinatorLayoutで困った時に確認するIssue Tracker

Android Design Support LibraryのCoordinatorLayoutを使った際に、困った既知(known issue)の問題をまとめます。

画面回転でBehaviorが正常に表示されない

AndroidManifest.xmlで、ActivityにconfigChanges属性で画面回転での再生成を追加すると、Behaviorが正常に表示されないことがあります。
ユースケースとしてはLandscapeからPortraitの画面回転で、現象が発生します。


この現象は、すでに本家Issue Trackerに登録されています。
CoordinatorLayout in design support library does not update child size on rotation
layout_behavior view height doesn't restore when keyboard goes down / ActionBar ActionView partially visible

AppBarLayoutがアニメーションしない

タッチを止めると、次のようにAppBarLayoutの部分が中途半端に残ってしまうことがあります。
Google Playアプリのようにアニメーションで全部消す/表示するには、タッチイベントとAppBarLayoutのオフセット位置、およびBehaviorのonNestedFlingを組み合わせて実装しないといけないのかな?
(ベストプラクティスを教えて欲しい)

Toolbar should settle when only partially scrolled

2015年6月6日土曜日

Android Support library v22.2で追加されたTextInputLayoutを使う

Material DesignのText fieldアニメーションが楽々に実装できるレイアウトです。
http://www.google.com/design/spec/components/text-fields.html#text-fields-single-line-text-field


実装は非常に簡単で、EditTextをTextInputLayutで囲うだけです。
    <android.support.design.widget.TextInputLayout
            android:id="@+id/textInputLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:hintTextAppearance="@style/TextInputLayoutHintAppearance">
        <EditText
                android:id="@+id/editText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"
                android:hint="HintText"
                android:ems="10"/>
    </android.support.design.widget.TextInputLayout>




各パーツはマテリアルカラーに準じています。

2015年5月29日金曜日

Android Support library v22.2で追加されたFloatingActionButtonを使う

早朝のGoogle I/O 2015のKeynoteと共に最新のAndroid Support libraryがリリースされました。
注目すべきはdesignパッケージです。本格的にマテリアルデザインのコンポーネントが追加されています。

http://developer.android.com/tools/support-library/index.html

Libのインポート

Android StudioでのDesign Support Libraryの追加方法は以下を参照、ですがTYPO(5/29時点)がありますので注意が必要です。
http://developer.android.com/tools/support-library/features.html#design

    compile 'com.android.support:design:22.2.0'

FloatingActionButton

次のように、レイアウトから使用可能です。

    <android.support.design.widget.FloatingActionButton
            android:id="@+id/floating_action_button"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:src="@drawable/XXXX"
            android.support.design:backgroundTint="@color/fab_bg"
            android:contentDescription="@string/XXXX"/>
FABのカラーはデフォルト:colorAccentです。もしカラーを変更する場合はandroid.support.design:backgroundTint属性でカラーを指定します。


備考

Design Support Libraryはリリースされたばかりで、まだまだissueが沢山あります。
Lollipop端末でFABを確認したところ、Shadowが正しく表示されませんでした。
FAB doesn't have shadow on Lollipop https://code.google.com/p/android/issues/detail?id=175068 The FloatingActionButton has different margins on Lollipop and pre-Lollipop. https://code.google.com/p/android/issues/detail?id=175330
動作がおかしい場合は、issue trackerを確認することをお勧めします。

2015年4月26日日曜日

IntentsTestRuleを使って、Intentのテストを行う

IntentsTestRuleについて

IntentsTestRuleは、startActivity()でセットしたIntentのデータをテストすることができます。
このクラスはActivityTestRuleを継承したクラスで、各Testの実行前にEspresso-Intentsを初期化し、実行後にEspresso-Intentsをリリースします。
各テスト後にActivityはfinish()されます。

build.gradleにEspresso-Intentsライブラリを追加します。
    androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.1'

サンプルソース

次はユーザー操作によって、Intent.ACTION_CALLのIntentが発生したかどうかテストするサンプルプログラムです。
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityIntentTest {

    @Rule
    public IntentsTestRule<MainActivity> mActivityRule = new IntentsTestRule<>(
            MainActivity.class);

    @Before
    public void stubAllExternalIntents() {
        // By default Espresso Intents does not stub any Intents. Stubbing needs to be setup before
        // every test run. In this case all external Intents will be blocked.
        intending(not(isInternal()))
                .respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
    }

    @Test
    public void callPhone() {
        // call action
        onView(withId(R.id.callButton)).perform(click());

        // test
        intended(allOf(
                hasAction(Intent.ACTION_CALL),
                hasData("tel:0123456789"),
                toPackage("com.android.server.telecom")));

    }
}
テストクラスは次のように作成します。
  • テストクラスにRunWithアノテーションをつける
  • IntentsTestRuleを生成する、Ruleアノテーションをつける

Intentが発生したかどうかは、次のように判定します。
  • intendedメソッドで意図したIntentが発生しているかチェックする
  • matchメソッドはこちらを参照


  • Activity起動時のIntentセット

    テストを行うActivityの起動用Intentが必要な場合、IntentsTestRule#getActivityIntentメソッドをオーバーライドしてIntentを返す。
        @Rule
        public IntentsTestRule<MainActivity> mActivityRule = new IntentsTestRule<>(MainActivity.class) {
    
            /**
            * Activity起動用Intent
            */
            @Override
            protected Intent getActivityIntent() {
                Intent intent = new Intent();
                // Activity起動用のパラメータをセット
                intent.putExtra(KEY_DATA,data);
                return intent;
            }
        };
    

    参考サイト:
    https://github.com/googlesamples/android-testing

    2015年3月1日日曜日

    EspressoでToast表示のチェックをする

    公式ページにアプリケーションLayer以外のチェック方法が載っています。
    Using inRoot to target non-default windows
    https://code.google.com/p/android-test-kit/wiki/EspressoSamples#Using_inRoot_to_target_non-default_windows

    onView(withText("South China Sea"))
      .inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView()))))
      .perform(click());
    

    上記の方法でもToast表示のチェックは行えますが、「non-default windows」であってToastの指定ではありません。
    ということで、自作してしまいましょう。

    ToastはWindowManager.LayoutParams.TYPE_TOASTというパラメータを持っています。
    これは表示するLayerを指定するものです。
    次はToast Layerを指定するMatcherのサンプルプログラムです。

        /**
         * Matcher that is Toast window.
         */
        public static Matcher<Root> isToast() {
            return new TypeSafeMatcher<Root>() {
    
                @Override
                public void describeTo(Description description) {
                    description.appendText("is toast");
                }
    
                @Override
                public boolean matchesSafely(Root root) {
                    int type = root.getWindowLayoutParams().get().type;
                    if ((type == WindowManager.LayoutParams.TYPE_TOAST)) {
                        IBinder windowToken = root.getDecorView().getWindowToken();
                        IBinder appToken = root.getDecorView().getApplicationWindowToken();
                        if (windowToken == appToken) {
                            // windowToken == appToken means this window isn't contained by any other windows.
                            // if it was a window for an activity, it would have TYPE_BASE_APPLICATION.
                            return true;
                        }
                    }
                    return false;
                }
            };
        }
    

    EspressoのViewMatchersモジュールを自作する

    EspressoのViewMatchersクラスには、たくさんの判定モジュールが用意されています。
    ただ、JUnit作成時に「こんなチェックをしたいのに、標準で用意されていない」こともあります。
    このような場合、自作するしかありません。

    次のような作業が必要です。
    1. BoundedMatcherを実装したオブジェクトを戻り値とするモジュールを作成
    2. マッチしているかどうか判定するモジュール、matchesSafelyをオーバーライドして判定ロジックを作成
    3. 何を判定するMatcherなのかを記述するdescribeToをオーバーライドして実装

    Espressoのソースが公開されていますので、参考になります。
    ViewMatchersクラス:https://code.google.com/p/android-test-kit/source/browse/espresso/lib/src/main/java/com/google/android/apps/common/testing/ui/espresso/matcher/ViewMatchers.java

    次はTextViewのColorが一致しているかどうか判定するMatcherのサンプルプログラムです。
    public static Matcher<view> withTextColor(final int resourceId) {
    
            return new BoundedMatcher<view textview="">(TextView.class) {
                private int expectedColor = -1;
    
                private String resourceName;
    
    
                @Override
                protected boolean matchesSafely(TextView textView) {
                    if (expectedColor == -1) {
                        try {
                            expectedColor = textView.getResources().getColor(resourceId);
                            resourceName = textView.getResources().getResourceEntryName(resourceId);
                        } catch (Resources.NotFoundException ignored) {
                            // view could be from a context unaware of the resource id.
                        }
                    }
    
                    if (expectedColor != -1) {
                        return (expectedColor == textView.getCurrentTextColor());
                    } else {
                        return false;
                    }
                }
    
                @Override
                public void describeTo(Description description) {
                    description.appendText("with color from resource id: ");
                    description.appendValue(resourceId);
                    if (null != resourceName) {
                        description.appendText("[");
                        description.appendText(resourceName);
                        description.appendText("]");
                    }
                    if (-1 != expectedColor) {
                        description.appendText(" value: ");
                        description.appendText(String.valueOf(expectedColor));
                    }
                }
            };
        }
    

    2015年2月1日日曜日

    LocalBroadcastManagerを使って、アプリ内部にのみブロードキャストを行う

    LocalBroadcastManager

    LocalBroadcastManagerはアプリ内の同プロセスに限定して、Broadcastを行う事ができます。
    通常のsendBroadcastでブロードキャストと異なり、次のような利点があります。

    プライベートなデータをアプリ外に残す心配がない。
    他アプリがこのBroadcastを使う事ができない。(セキュリティホールの心配はしなくていい)
    通常のBroadcastに比べ、より効率的アプリ内部へブロードキャストが行える。

    注意点としては「同プロセス」に限定してブロードキャストを行います。言い換えれば、他プロセスにはブロードキャストは行えません。


    用途

    データ管理を行うModleクラスを作成する際、多くの人はServiceで実装すると思います。
    Serviceを使うまでもない軽微なModleなら、ObserverとしてLocalBroadcastManagerを利用してデータの更新通知を行うのもありかと思います。


    サンプルソース

    こちらにJUnit付きのソースをアップしています。
    https://github.com/baroqueworksdev/MyApiDemo_AndroidStudio/commit/cf08208cfd84b916480a08acf6f43fd791ca7da0

    public class LocalBroadcastController {
        private LocalBroadcastManager mLocalBroadcastManager;
        private IntentFilter mIntentFilter;
        private OnLocalBroadcastController mOnLocalBroadcastController;
    
        public interface OnLocalBroadcastController {
            public void onReceive(Context context, Intent intent);
        }
    
        /**
         * Constructor
         *
         * @param context  Context
         * @param filter   Intent Filter which need to receive an action
         * @param listener onReceive
         */
        public LocalBroadcastController(Context context, IntentFilter filter, OnLocalBroadcastController listener) {
            mLocalBroadcastManager = LocalBroadcastManager.getInstance(context);
            mIntentFilter = filter;
            mOnLocalBroadcastController = listener;
        }
    
        /**
         * Register Receiver
         */
        public void registerReceiver() {
            mLocalBroadcastManager.registerReceiver(mReceiver, mIntentFilter);
        }
    
        /**
         * Unregister Receiver
         */
        public void unregisterReceiver() {
            mLocalBroadcastManager.unregisterReceiver(mReceiver);
        }
    
    
        private BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                mOnLocalBroadcastController.onReceive(context, intent);
    
            }
        };
    
    }
    

    2015年1月25日日曜日

    Android StudioでZXingのライブラリを使う

    Android StudioでZXingのライブラリを使う設定です。
    非常に簡単で、アプリのbuild.gradleに追加するだけです。

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:21.0.2'
    +    compile 'com.google.zxing:core:3.1.0'
    +    compile 'com.google.zxing:android-integration:3.1.0'
    
    }
    

    2015年1月17日土曜日

    Volleyのリクエストにパラメータとヘッダーの値を追加する方法

    Volleyのリクエストにパラメータとヘッダーの値を追加する方法です。
    StringRequestクラスの親クラスであるRequestクラスに、次のようなメソッドがあります。

         /**
         * Returns a list of extra HTTP headers to go along with this request. Can
         * throw {@link AuthFailureError} as authentication may be required to
         * provide these values.
         * @throws AuthFailureError In the event of auth failure
         */
        public Map<String, String> getHeaders() throws AuthFailureError {
            return Collections.emptyMap();
        }
    
         /**
         * Returns a Map of parameters to be used for a POST or PUT request.  Can throw
         * {@link AuthFailureError} as authentication may be required to provide these values.
         *
         * <p>Note that you can directly override {@link #getBody()} for custom data.</p>
         *
         * @throws AuthFailureError in the event of auth failure
         */
        protected Map<String, String> getParams() throws AuthFailureError {
            return null;
        }
    

    StringRequestを生成する際、getHeaders()とgetParams()をオーバーライドすれば、POSTパラメータとヘッダーの値を追加することができます。
    次のソースはオーバーライドによって値を渡すサンプルです。


        /**
         * Request(StringRequest) with params
         *
         * @param url      request url
         * @param listener listener for Response or Error
         * @param params   value of setting Http Params
         * @param headers  value of setting Http headers
         */
        public void get(String url, final ResponseListener listener, final Map<String, String> params
                , final Map<String, String> headers) {
     
            StringRequest request = new StringRequest(url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            listener.onResponse(s);
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            listener.onErrorResponse(volleyError);
                        }
                    }
            ) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    return params;
                }
     
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return headers;
                }
            };
     
            mRequestQueue.add(request);
        }
    

    2014年12月20日土曜日

    Android Studioで開発効率をアップしてくれるPlugins

    Android Layout ID Converter

    レイアウトxmlファイルからandroid:idを抽出して、findViewByIdを楽々コピペしてくれるPluginです。
    詳しくは作成者さまの動画をご覧ください。



    Android Parcelable code generator

    データクラスを簡単にParcelable化してくれるPluginです。
    https://github.com/mcharmas/android-parcelable-intellij-plugin/

    ※随時、更新予定

    Android StudioでVolleyを使用するための設定方法

    Volleyについて

    Volleyは簡単に素早くネットワーク処理を実装することができるHTTPライブラリです。次のような利点があります。

    • ネットワークリクエストの自動スケジューリング
    • 多重同時ネットワーク通信
    • メモリを使用したリクエストのキャッシュ機能
    • リクエストの優先順位をサポート
    • キャンセルリクエストAPI
    • ネットワークから非同期にデータのフェッチを必要とするUIに正確に行う
    • デバッグ機能

    [*1] Transmitting Network Data Using Volley: http://developer.android.com/training/volley/index.html

    Volleyのセットアップ

    VolleyライブラリはAOSPのframeworks/volleyに公開されています。現時点では、このリポジトリからソースをダウンロードして、Android Studioのワークスペースに組み込みます。

    git submodule add https://android.googlesource.com/platform/frameworks/volley modules/volley
    

    git submoduleコマンドにより、プロジェクトのサブモジュールとしてmodules/volleyに格納します。以後、volleyサブプロジェクトを更新する場合は次のコマンドを実行します。

    git submodule update
    

    setting.gradleにVolleyライブラリを追加

     include ':app'
    +include ':modules:volley'
    

    アプリケーションのbuild.gradleのdependeciesにVolleyライブラリを追加

     dependencies {
         compile 'com.android.support:support-v4:19.1.0'
         androidTestCompile 'com.android.support:support-v4:19.1.0'
         androidTestCompile 'com.android.support:support-v4:19.1.0'
    +    compile project(':modules:volley')
     }
    

    上記の設定を終えたら、Sync Project with Gradle Filesを実行してビルドを行います。

    2014年11月23日日曜日

    Android 5.0(マテリアルデザイン) ActionBarの背景色をカスタマイズする

    査読必須サイト

    I/O 2014 アプリに学ぶマテリアルデザイン
    Customize the Color Palette
    Google本家のスタイルガイド


    各パーツと要素の指定


    以下、各パーツと要素名です。style.xmlにて各要素の色を指定します。


    AppCompat使用時の指定

    次はStatsuBarとActionBarの背景色を指定するサンプルです。styles.xmlに記載しました。

    <resources>
    
        <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    
            <!-- your app branding color for the app bar -->
            <item name="colorPrimary">@color/primary</item>
            <!-- darker variant for the status bar and contextual app bars -->
            <item name="colorPrimaryDark">@color/primary_dark</item>
        </style>
    
    </resources>
    

    AppCompatを使用時は「name="android:colorPrimary"」でないことに注意してください。


    サンプル画面

    次のようにcolor.xmlに定義を追加してみました。
    色はGoogle本家のスタイルガイド
    から適用しました。

    <resources>
    
        <!-- Material -->
        <color name="primary">#4caf50</color>
        <color name="primary_dark">#388e3c</color>
    
    </resources>
    



    StatsuBarとActionBarの背景色がマテリアルデザインっぽくなりました。

    Android Studioのコードフォーマッタを設定する

    チーム開発を行う場合、フォーマッタは重要です。
    メンバー全員のフォーマッタを統一しないとソース管理で痛い目にあいます。

    AOSPのCodeStyleを使用する

    AOSPにAndroid用のCodeStyleがアップされています。
    こちらからDLしましょう。
    https://android.googlesource.com/platform/development/+/master/ide/intellij/codestyles/

    AndroidStyle.xmlを以下のディレクトリに格納します。
    (Windowsの場合)
    C:\Users\[USER_NAME]\.AndroidStudioBeta\config\codestyles

    (Macの場合)
    ~/Library/Preferences/AndroidStudio/codestyles
    Android StudioのFile->Settingsから設定を行います。



    Eclipse Code Formatterを使用する

    Eclipseと共存で開発をする場合、フォーマッタを統一しましょう。(ソース管理上のトラブルを防ぐため)
    Pluginsから「Eclipse Code Formatter」をインストールします。




    File - Settings - Eclipse Code Formatterを開いて設定を行います。




    2014年7月27日日曜日

    ViewFlipperの自動フリップのフリップタイミングをハンドリングする

    ViewFlipperの自動フリップで、フリップタイミングをハンドリングする方法です。
    ViewFlipperクラスは、フリップタイミングを直接ハンドリングするリスナーが用意されていません。
    そのため、VewFlipper#getInAnimation()でインアニメーションを制御するAnimationクラスを取得し、このクラスにリスナーをセットします。


    プログラムはこんな感じ
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
            View view = inflater.inflate(R.layout.fragment_flashing_card, null);
            mVewFlipper = (ViewFlipper) view.findViewById(R.id.viewFlipper1);
    
            mVewFlipper.setAutoStart(true);
            mVewFlipper.setInAnimation(getActivity(), android.R.anim.slide_in_left);
            mVewFlipper.getInAnimation().setAnimationListener(this);
            mVewFlipper.setFlipInterval(2000);
    
            return view;
        }
    
        @Override
        public void onAnimationEnd(Animation animation) {
        }
    
        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    
        @Override
        public void onAnimationStart(Animation animation) {
        }