標籤:android開發 broadcastreceiver
Android開發中,通常會使用BroadcastReceiver來接受Push推送訊息。當APP收到推播通知時,我們需要在通知的點擊事件中加入自己的邏輯。比如跳轉到MainActivity。
比如下面的代碼(注意紅色部分):
public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) { String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID); Log.d(TAG, "[JPushReceiver] 接收Registration Id : " + regId); //send the Registration Id to your server... } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) { Log.d(TAG, "[JPushReceiver] 接收到推送下來的自訂訊息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE)); } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) { Log.d(TAG, "[JPushReceiver] 接收到推送下來的通知"); int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID); Log.d(TAG, "[JPushReceiver] 接收到推送下來的通知的ID: " + notifactionId); } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) { Log.d(TAG, "[JPushReceiver] 使用者點擊開啟了通知"); JPushInterface.reportNotificationOpened(context, bundle.getString(JPushInterface.EXTRA_MSG_ID)); // 開啟自訂的Activity Intent i = new Intent(context, MainTabActivity.class); i.putExtras(bundle); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) { Log.d(TAG, "[MyReceiver] 使用者收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA)); //在這雷根據 JPushInterface.EXTRA_EXTRA 的內容處理代碼,比如開啟新的Activity, 開啟一個網頁等.. } else { Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction()); }}
使用Activity以外的content來startActivity,必須指定為Intent.FLAG_ACTIVITY_NEW_TASK。
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
我們可以嘗試下使用Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT,會拋出以下異常:
ERROR/AndroidRuntime(7557): java.lang.RuntimeException: Unable to start receiver com.wcc.Wakeup: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
更多關於Intent的flag,可以參考:http://developer.android.com/reference/android/content/Intent.html
所以只能使用FLAG_ACTIVITY_NEW_TASK。使用這個還有個問題,就是會新開啟一個MainActivity。如何解決這個問題?
其實很簡單在AndroidManifest.xml中將MainActivity定義為:
android:launchMode="singleTask" 即可:
<activity android:name="com.withiter.quhao.activity.MainTabActivity" android:launchMode="singleTask" android:label="@string/app_name" android:screenOrientation="portrait">
這樣每次開啟推送,就不會出現2個activity的情況了。
更多關於activity的launchMode可以參考:http://developer.android.com/guide/topics/manifest/activity-element.html#lmode
好了今天這個破事就到這裡,其實android開發就這麼點破事。關於其他破事,見專欄:
更多Android開發的破事,請看專欄:《Android開發那點破事》