比如下面的代碼(注意紅色部分):
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開發那點破事》