2010-03-08 106 views
2

在我的應用程序後臺服務啓動,並從該服務,我想設置狀態欄通知,該服務已經啓動下面是代碼:處理狀態欄通知

Context context = getApplicationContext(); 
    String ns = Context.NOTIFICATION_SERVICE; 
    int icon = R.drawable.icon; 
    CharSequence tickerText = "Hello"; 
    long when = System.currentTimeMillis(); 
    Notification notification = new Notification(icon, tickerText, when); 
    CharSequence contentTitle = "My notification"; 
    CharSequence contentText = "Hello World!"; 
    Intent notificationIntent = new Intent(MyService.this, MyClass.class); 
    notificationIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK); 

    PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0); 

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); 
    mNotificationManager.notify(1, notification); 

通知顯示在狀態欄,但我只點擊那個MyClass.class沒有被解僱。並且在日誌貓中它顯示 「輸入管理器服務窗口已經集中忽略了焦點...」

因此PLZ提供瞭解決方案。

在此先感謝

回答

2

我不知道你所說的「MyClass.class不解僱」的意思,但如果它已經加載和你希望的onCreate被稱爲再次,你可以期待錯誤的結果。我做的非常相似,讓代碼從通知觸摸我已經運行活動的派生類執行的東西,我通過PendingIntent.FLAG_UPDATE_CURRENT作爲第四個參數的構造函數的PendingIntent

PendingIntent contentIntent = PendingIntent.getActivity(YourService.this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

,我把我的代碼執行的活動如下方法:

@Override 
public void onNewIntent(Intent intent) 
{ 
    super.onNewIntent(intent); 

    // your code here 

} 
+2

'FLAG_UPDATE_CURRENT'隻影響其他'PendingIntents'。 'onNewIntent()',雖然是很重要的 - 如果該活動已經在運行,它不會收到'的onCreate()',因爲它已經被創建。 – CommonsWare 2010-03-08 15:16:52

1

首先,不要使用getApplicationContext()。你ServiceContext,以及「應用程序上下文」一般是無用的地方,你需要一個Context

其次,我懷疑你需要FLAG_ACTIVITY_NEW_TASK

Here is a sample application表示使用Notifications。註冊爲類似`Intents`(例如,同樣的動作,同樣的部件)