簡體   English   中英

Android:點擊狀態欄通知的事件

[英]Android: Click event for Status bar notification

我有以下代碼來創建狀態欄通知:

public void txtNotification(int id, String msg){
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(android.R.drawable.sym_action_email, msg, System.currentTimeMillis());

    // The PendingIntent will launch activity if the user selects this notification
    Intent intent = new Intent(this, MainActivity.class)
    intent.putExtra("yourpackage.notifyId", id);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 0);

    notification.setLatestEventInfo(this, "title", msg, contentIntent);

    manager.notify(id, notification);
}

單擊通知時,我想調用一個方法,最好能夠訪問通知的id。

提前致謝,

蒂姆

(編輯:我在閱讀完第一個答案后更新了我的代碼,但我仍然不知道如何傾聽意圖)

我認為處理通知點擊的最佳方式(可能是唯一的方法?)是在PendingIntent調用的類中定義一個方法(在本例中為MainActivity)。 您可以在將其傳遞到getActivity()之前修改您的意圖以包含通知的ID:

// The PendingIntent will launch activity if the user selects this notification
Intent intent = new Intent(this, MainActivity.class)
intent.putExtra("yourpackage.notifyId", id);
PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 0);

然后在MainActivity中監視此意圖,並調用您在類中定義的方法來處理通知。 您可以從傳入的Intent中提取id。

更新:

為了讓您的Activity處理通知,您需要首先在AndroidManifest.xml文件中定義Activity,包括您需要的任何intent過濾器。 然后在Activity的onStart()中,您可以從傳入的intent中提取額外內容,並根據該數據進行操作。 這是一個高級概述,因此我建議您閱讀開發指南的部分內容以熟悉這些概念。 以下頁面是一個很好的起點:

http://developer.android.com/guide/topics/fundamentals.html

另外,“yourpackage”應替換為包含您的類的包的名稱,例如“com.project.foo”。

對於像我這樣的假人:在MainActivity上獲取這個yourpackage.notifyId:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle intent_extras = getIntent().getExtras();
        if (intent_extras != null && intent_extras.containsKey("yourpackage.notifyId"))
        {
          //Do the codes
        }

}

在我的情況下 - 使用它來確定誰正在打開我的主動,用戶或來自通知的電話,由GcmIntentService ... PS我已經使用了沒有“youpackage”的名字,也可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM