您可以在GCMIntentService意圖類的onMessage偵聽器的SharedPreferences中保存一些數據。 GCM監聽器畢竟屬於你的軟件包應用。 保存的內容取決於您的應用程序和消息載荷,但它可能是您想要的任何內容。 然後,在您點擊通知時啓動的Activity的onCreate函數中,您可以閱讀Shared Preferences以查看您是否來自GCM通知。請記住清除SharedPreferences中保存的變量,以便下次用戶打開應用程序時,它會正確顯示內容。
你有一個例子。不幸的是,我現在無法嘗試,但看到這個想法很有用。它與G2DM非常相似,所以你必須在你的情況下尋找相應的東西。
public class GCMIntentService extends GCMBaseIntentService {
/*... other functions of the class */
/**
* Method called on Receiving a new message
* */
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("your_message");
// notifies user
generateNotification(context, message);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
// Save your data in the shared preferences
SharedPreferences prefs = getSharedPreferences("YourPrefs", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = prefs.edit();
prefEditor.putBoolean("comesFromGCMNotification", true);
prefEditor.commit();
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
感謝您的迴應。 :-)這與我已經在做的事很相似,儘管顯然沒有使用我們正在談論的sharedprefs。我有什麼麻煩包裝我的頭是「comeFromGCMNotification」部分,以及我可以告訴用戶是否從通知啓動或不。在我看來,在用戶得到通知並設置了「comeFromGCMNotification」之後,如果他們啓動應用程序而沒有選擇通知,那麼「comeFromGCMNotification」仍然是真實的,並且無論什麼處理仍將完成。我在這裏的推理中錯了嗎? – MrTristan 2013-03-11 21:14:56
@MrTristan檢查你是否在兩個地方使用相同的首選項(Activity和GCMIntentService)。在我的例子中,他們被稱爲「YourPrefs」。當您詢問不存在的偏好時,您也可以檢查默認返回值。爲了測試這個,使用一個字符串來代替「comeFromGCMNotification」的布爾值,並檢查結果是否真的是你放置的而不是默認值(可能是一個空字符串或可能爲空)。 – Esparver 2013-03-11 21:20:10
我想我錯誤地評論了我的評論。讀取comeFromGCMNotification的價值不是問題......這是我認爲,在概念層面上,流程將是錯誤的。我認爲,收到通知後,如果您在收到通知後設置了該偏好,則在您未啓動通知時啓動該應用程序仍然會發生這種情況......我希望能夠根據您是否啓動通過選擇通知或通過主屏幕啓動應用程序。 – MrTristan 2013-03-12 13:50:05