2013年5月22日水曜日

Google I/O 2013 - Android : Android Protips: Making Apps Work Like Magic

Android Protips: Making Apps Work Like Magic

導入部分の話が面白い
  • ムーアの法則
  • 昔の PC の話とか
  • 昔のネット通信のモデムの音とか
  • アーサー・C・クラークの言葉
    "Any significantly advanced technology is indistinguishable from magic." "高度に発達したテクノロジーは魔法と見分けがつかない"
  • 5年前まだ Android がないときにブログに書いた未来の予想が悲観的すぎた、予想よりも早く実現しつつある
  • アーサー・C・クラークの言葉その2
    "The only way of discovering the limits of the possible is to venture a little way past it into the impossible."
スポーツで相手の進行方向を予測してパスを出すように、リリース時の状況を予測しよう(ライバルは今よりアップグレードしてるだろう、デバイスの分布はどうだろう。。。)

Android Beam の話
# NFC の機能が魔法っぽいってはなしかな

Lockscreen Widget
# Lockscreen Widget って魔法っぽいかな。。。?

"Context isn't important, it's critical."

デバイスはユーザーのことを知っている。デバイスはどんなニュースや本を読んで、どんな音楽を聴いて、どんな映画を見て、どんなゲームをして、だれが友達で、どこで予定があるのか知っている
魔法のような体験を作るための Context を用意する、すごい可能性がここにはある

どんな Context が使える?
例えば Location

Location based Services

Google Play Services の一部として新しい Location based Services をリリースしたよ!
すごい簡単に使えるよ
単にクライアントを作って接続すれば OK
  1. private void connectLBS() {  
  2.   int gpsExists = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);  
  3.   if(gpsExists == ConnectionResult.SUCCESS) {  
  4.     mLocationClient = new LocationClient(thisthisthis);  
  5.     mLocationClient.connect();  
  6.   }  
  7. }  
  8.   
  9. @Override  
  10. public void onConnected(Bundle connectionHint) {  
  11.   requestUpdates(mLocationClient);  
  12. }  
どの provider (位置の)が有効かどうかチェックする必要はない
Google Play Services の一部である Fused Location Provider が最もいい結果を返してくれる

Geofencing
  1. List<Geofence> fenceList = new ArrayList<Geofence>();  
  2.   
  3. // TODO Repeat for all Geofences  
  4. Geofence geofence = new Geofence.Builder()  
  5.   .setRequestId(mKey)  
  6.   .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |  
  7.                       Geofence.GEOFENCE_TRANSITION_EXIT)  
  8.   .setCircularRegion(latitude, longitude, GEOFENCE_RADIUS)  
  9.   .setExpirationDuration(Geofence.NEVER_EXPIRE)  
  10.   .build();  
  11.   
  12. fenceList.add(geofence);  
  13.   
  14. mLocationClient.addGeofences(fenceList, pendingIntent, addGeofenceResultListener);  


Activity Recognition
  1. Intent intent = new Intent(this, ActivityRecognitionIntentService.class);  
  2. intent.setAction(MyActivity.ACTION_STRING);  
  3.   
  4. PendingIntent pi =  
  5.   PendingIntent.getService(this0, intent, PendingIntent.FLAG_UPDATE_CURRENT);  
  6.   
  7. mActivityRecognitionClient.requestActivityUpdates(interval, pi);  
  1. @Override  
  2. protected void onHandleIntent(Intent intent) {  
  3.   if(intent.getAction() == MyActivity.ACTION_STRING) {  
  4.     if(ActivityRecognitionResult.hasResult(intent)) {  
  5.       ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);  
  6.       DetectedActivity detectedActivity = result.getMostProbableActivity();  
  7.       int activityType = detectedActivity.getType();  
  8.       if (activityType == DetectedActivity.STILL)  
  9.         setUpdateSpeed(PAUSED);  
  10.       else if (activityType == DetectedActivity.IN_VEHICLE)  
  11.         setUpdateSpeed(FASTER);  
  12.       else  
  13.         setUpdateSpeed(REGULAR);  
  14.     }  
  15.   }  
  16. }  



Google+ について

友達の状態とかがとれるのでもっと Context にあったことができるという話
(どうなんでしょうね。。。)

知りすぎると Uncanny App Valley に落ちるよ
Google Now は何をするのかはっきりわかるけど、もしソフトキーボードが自分の好きなスポーツを勧めてきたりしたら気持ち悪いよねってこと

Rob Foster の言葉
"Introducing visceral elements into an app.. will make it speak to the subconscious."


人生は単になにをするかだけではなく、何を体験するかだから

カフェで人は単にコップのなかの水を買っているわけではなく。その周りにひろがる体験(雰囲気とか香りとか見た目とかもろもろ)を買っている

アプリでは何ができる?
・テイストはだめだよね
・香り、、、もだめだよね、来年どうなるかみよう
ということで
・見た目
・音
・タッチ
にフォーカスしよう

背後にある哲学、スピリット、ビジョンを理解しよう
https://developer.android.com/design をみよう


Text to Speech(TTS)

セットアップは簡単
  1. private void initTextToSpeech() {  
  2.   Intent intent = new Intent(Engine.ACTION_CHECK_TTS_DATA);  
  3.   startActivityForResult(intent, TTS_DATA_CHECK);  
  4. }  
  5.   
  6. @Override  
  7. protected void onActivityResult(int request, int result, Intent data) {  
  8.   if(request == TTS_DATA_CHECK && result == Engine.CHECK_VOICE_DATA_PASS) {  
  9.     tts = new TextToSpeech(thisnew OnInitListener() {  
  10.   
  11.       @Override  
  12.       public void onINit(int status) {  
  13.         if (status == TextToSpeech.CUSSCESS)  
  14.           ttsIsInit = true;  
  15.         
  16.       }  
  17.     });  
  18.   }  
  19.   else {  
  20.     startActivity(new Intent(Engine.ACTION_INSTALL_TTS_DATA);  
  21.   }  
  22. }  
  23.   
  24. private void say(String text) {  
  25.   if (tts != null && ttsIsInit) {  
  26.     tts.speak(text, TextToSpeech.QUEUE_ADD, null);  
  27.   }  
  28. }  
“そのアプリ”を使う理由になる機能をいれよう


Speech Recognition
  1. private void requestVoiceInput() {  
  2.   Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);  
  3.   intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,  
  4.                   RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);  
  5.   intent.putExtra(RecognizerIntent.EXTRA_PROMPT,  
  6.                   getString(R.string.voice_input_prompt);  
  7.   intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,  
  8.                   Locale.ENGLISH);  
  9.   startActivityForResult(intent, VOICE_RECOGNITION);  
  10. }  
  11.   
  12. @Override  
  13. protected void onActivityResult(int request, int result, Intent data) {  
  14.   if (request == VOICE_RECOGNITION && result == RESULT_OK) {  
  15.     ArrayList<string> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);  
  16.     String mostLikelyResult = results[0];  
  17.     useSpeechInput(mostLikelyResult);  
  18.   }  
  19. }  
  20. </string>  
ここでは、もっともありえそうだとシステムが認識した答え(スタックの一番最初)をつかっているけど、Context を利用して候補のなかからより正しいものを選択するべき


48dip のレイアウト

どれがタッチできるのかユーザーがわかるようにする = ちゃんと state に応じた画像を用意しよう

android:foreground="?android:selectableItemBackground"


Simple Accessibility Support
  1. <Button  
  2.   ...  
  3.   android:contentDescription="@string/my_button_description"  
  4.   />  



Custom Control Accessibility Support
  1. public void setHeading(float heading) {  
  2.   mHeading = heading;  
  3.   sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);  
  4. }  
  5.   
  6. @Override  
  7. public boolean dispatchPopulateAccessibilityEvent(final AccessibilityEvent e) {  
  8.   super.dispatchPopulateAccessibilityEvent(e);  
  9.   String heading = String.valueOf(mHeading);  
  10.   if(heading.length() > AccessibilityEvent.MAX_TEXT_LENGTH) {  
  11.     heading = heading.subString(0, AccessibilityEvent.MAX_TEXT_LENGTH);  
  12.   }  
  13.   event.getText().add("Heading is " + heading + " degree");  
  14.   return true;  
  15. }  



ジェスチャーを使う Android Training の Using Touch Gestures クラスがおすすめ

Jazz Hands
  1. @Override  
  2. public boolean onTouchEvent(MotionEvent event) {  
  3.   int action = event.getAction();  
  4.   
  5.   if (event.getPointerCount() > 1) {  
  6.     int actionPointerId = action & MotionEvent.ACTION_POINTER_ID_MASK;  
  7.     int actionEvent = action & MotionEvent.ACTION_MASK;  
  8.   
  9.     int pointerIndex = event.findPointerIndex(actionPointerId);  
  10.     int xPos = (int) event.getX(pointerIndex);  
  11.     int yPos = (int) event.getY(pointerIndex);  
  12.     // TODO Magic.  
  13.   }  
  14. }  


ルールを破るときは気をつけて、かならずしも positive な反応になるとは限らない
→ Google Play の developer console に追加された ALPHA TESTING, BETA TESTING 機能を使おう

だれがもっともバリューゾーンのユーザーなのかを知ろう、国、言語、デバイス、、、
→ Analytics を使おう

# FFっぽい動画でてきたでw





# Google Quest Cheat Codes...w




スマートフォンの一番の魔法は常にネットに繋がっていることじゃないかな
更新ボタンを eliminate するのはやめよう
ユーザーが更新しようとする前に更新しといてほしいよね

データのやりとりの理由としては
  • Client Updates
  • Server Updates
  • On-Demand Downloads
  • Cross-Device Updates
サーバー側の update については Google Cloud Messaging という強力なツールがある
Cross-Device updates にも GCM が使えるよ
キーノートのデモであったように Notification がデバイス間で同期するようになったよ


Google Cloud Messaging: Upstream
  1. GoogleCloudMessaging gcm = GoogleCloudMessaging.get(context);  
  2. gcm.send(to, msgId, data);  
サーバー側がよくわからない? Mobile Backend Starter を使おう


Client Updates にとてもいいものがあるよ、それが SyncAdapter
  1. public class MySyncAdapter extends AbstractThreadSyncAdapter {  
  2.   public MySyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {  
  3.     super(context, autoInitialize, allowParallelSyncs);  
  4.   }  
  5.   
  6.   public MySyncAdapter(Context context, boolean autoInitialize) {  
  7.     super(context, autoInitialize);  
  8.   }  
  9.   
  10.   @Override  
  11.   public void onPerformSync(Account account, Bundle extras, String authority,  
  12.     ContentProviderCLient provider, SyncResult syncResult) {  
  13.       // TODO Synchronize your data between client adn server.  
  14.     }  
  15.   }  
# ネットが繋がっていないと繋がったときに処理をするよう待ってくれたりするらしい


Abstract Account Manager
  1. public class MyAccountAuthenticator extends AbstractAccountAuthenticator {  
  2.   public static final String ACCOUNT_TYPE = "com.mycompany.myapp";  
  3.   public static final String ACCOUNT_NAME = "MY STUB ACCOUNT";  
  4.   
  5.   @Override  
  6.   public Bundle addAccount(AccountAuthenticatorResponse response, String accountType,  
  7.     String authTokenType, String[] requiredFeatures, Bndle options)  
  8.     throw NetworkErrorException {  
  9.   
  10.     AccountManager manager = AccountManager.get(activity);  
  11.     final Account account = new Account(ACCOUNT_NAME, ACCOUNT_TYPE);  
  12.     manager.addAccountExplicitly(account, nullnull);  
  13.     ContentResolver.setIsSyncable(account, authority, 1);  
  14.     ContentResolver.setSyncAutomatically(account, authority, true);  
  15.     return null;  
  16.   }  
  17.   
  18.   ...  
  19. }  
アカウントタイプに気をつける



Account Manager Service
  1. public class MyAuthenticationService extends Service {  
  2.   MyAccountAuthenticator mAuthenticator;  
  3.   
  4.   @Override  
  5.   public void onCreate() {  
  6.     mAuthenticator = new MyAccountAuthenticator(this);  
  7.   }  
  8.   
  9.   @Override  
  10.   public IBinder onBind(Intent intent) {  
  11.     return mAuthenticator.getIBinder();  
  12.   }  
  13. }  
Account Manager XML Config
  1. <account-authenticator xmlns:android="..."  
  2.   android:accountType="com.mycompany.myapp"  
  3.   android:icon="@drawable/icon"  
  4.   android:smallIcon="@drawable/miniicon"  
  5.   android:label="@string/app_name"  
  6.   />  
Content Provider
  1. public class MyContentProvider extends ContentProvider {  
  2.   
  3.   @Override  
  4.   public boolean onCreate() { return true; }  
  5.   
  6.   
  7.   @Override  
  8.   public String getType(Uri uri) { return "vnd.android.cursor.dir/vnd.myapp.items"; }  
  9.   
  10.   @Override  
  11.   public Cursor query(Uri uri, String[] projection, String selection,  
  12.     String[] selectionArgs, String sort) { return null; }  
  13.   
  14.   @Override  
  15.   public Uri insert(Uri uri, ContentValues initialValues) { return null; }  
  16.   
  17.   @Override  
  18.   public int delete(Uri uri, String where, String[] whereArgs) { return 0; }  
  19.   
  20.   @Override  
  21.   public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { return 0; }  
  22. }  
Manifest
  1. <provider android:authorities="com.mycompany.myapp.myauthority"  
  2.              android:name=".content_providers.PlaceDetailsContentProvider" />  
Sync Adapter XML Config
  1. <sync-adapter xmlns:android="..."  
  2.   android:contentAuthority="com.mycompany.myapp.myauthority"  
  3.   android:accountType="com.mycompany.myapp"  
  4.   android:userVisible="false"  
  5.   />  
Manifest
  1. <provider android:authorities="com.mycompany.myapp.myauthority"  
  2.              android:name=".content_providers.PlaceDetailsContentProvider" />  
  3.   
  4. <service android:name=".MyAuthenticationService" android:exported="true">  
  5.   <intent-filter>  
  6.     <action android:name="android.accounts.AccountAuthenticator" />  
  7.   </intent-filter>  
  8.   <meta-data  
  9.     android:name="android.accounts.AccountAuthenticator"  
  10.     android:resource="@xml/accountauth" />  
  11. </service>  
  12.   
  13. <service android:name=".MySyncService" android:exported="true">  
  14.   <intent-filter>  
  15.     <action android:name="android.content.SyncAdapter" />  
  16.   </intent-filter>  
  17.   <meta-data  
  18.     android:name="android.content.SyncAdapter"  
  19.     android:resource="@xml/sync_myapp" />  
  20. </service>  
Triggering Syncs
  1. final Account account = new Account(null, MyAccountAuthenticator.ACCOUNT_TYPE);  
  2. String authority = "com.mycompany.myapp.myauthority";  
  3.   
  4. mContentResolver.requestSync(account, authority, null);  
Periodic Repeating Syncs
  1. final Account account = new Account(null, MyAccountAuthenticator.ACCOUNT_TYPE);  
  2. String authority = "com.mycompany.myapp.myauthority";  
  3. long interval = 12 * 60 * 60// 12 hours (24hr by default).  
  4.   
  5. mContentResolver.addPeriodicSync(account, authority, null, interval);  
repeating syncs にする理由は、もしサーバーの update が毎日2時にあるとして、そこにアラームをかけてクライアントが同期するようにすると、その時間サーバーにすごい負荷がかかってしまう

時間をベースにして同期はやめよう
たとえネットに接続しなくても次のようにランダムな jitter を使おう


Update Window
  1. final Account account = new Account(null, MyAccountAuthenticator.ACCOUNT_TYPE);  
  2. String authority = "com.mycompany.myapp.myauthority";  
  3.   
  4. Random random = new Random();  
  5. int jitter = random.nextInt(60);  
  6.   
  7. long start = SystemClock.elapseRealtime() + interval - ((30 + jitter)*60000);  
  8.   
  9. alarmManager.setInexactRepeating(alamType, start, interval, pi);  
Acitvity Recognition: Pickup Trigger
  1. @Override  
  2. public void onReceive(Context context, Intent intent) {  
  3.   // Extract the Activity that's been detected.  
  4.   ActivityDetectionResult activity = ActivityDetectionResult.extractResult(intent);  
  5.   
  6.   if(activity != null) {  
  7.     ActivityType activityType = activity.getMostProvavleActivity().getType();  
  8.     if (ActivityType.valueOf(activityTypeString) == ActivityType.TILTING)  
  9.       context.startService(new Intent(context, DailyUpdateService.class);  
  10.   }  
  11. }  



On-demand download

SyncAdapter with Calls to Other Updates
  1. @Override  
  2. public void onPerformSync(Account account, Bundle extras, String authority,  
  3.   ContentProviderClient provider, SyncResult result) {  
  4.   
  5.   downloadServerSideSync();  
  6.   uploadClientSideSync();  
  7.   transmitBatchedAnalytics();  
  8.   executePrefetch();   
  9.   retryFiledTransfers();  
  10. }  





# 1時間という長いセッションだったし、最後のほうはコードが多かったな # 3番目の動画がいいね



0 件のコメント:

コメントを投稿