0

我創建了一個服務,該服務在特定時間間隔後顯示狀態欄通知。 我也創建了廣播接收器,當手機重新啓動或開機時啓動服務。我面臨的問題是,當手機重新啓動時,我看到欄中的通知,但之後應用程序啓動。我不希望應用程序自行啓動,它只應在用戶單擊通知時啓動。狀態欄通知在電話啓動時打開活動

我對撒施接收器代碼:

@Override 
    public void onReceive(Context context, Intent intent) { 



     if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { 


      try 
      { 
       Intent intent1 = new Intent(context, NotificationService.class); 
       context.startService(intent1); 

      } 
      catch(Exception e) 
      { 

      } 


     } 

    } 

我通知代碼是:

public static void showNotification(Context context) 
    { 


    NotificationManager notificationManager = (NotificationManager)   context.getSystemService(Context.NOTIFICATION_SERVICE); 

    Notification notification = new Notification(R.drawable.ic_launcher, "Pull Me Down!!", 1000); 
    Intent intent = new Intent(context,X.class); 
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0); 
    notification.setLatestEventInfo(context, "I came!!", "My First Notifcation" , pendingIntent); 
    notificationManager.notify(MY_ID, notification); 

    } 

我在我的服務onCreate調用上述方法。也稱它在我的X活動類:

NotificationService.setActivity(StatusBarNotificationActivity.this); 
       startService(new Intent(getApplicationContext(), NotificationService.class)); 

但是不知道爲什麼,當手機開始通知顯示,但幾秒鐘後,X活動也將啓動。

回答

1

解決了它,只是在方法外聲明瞭NotificationManagerNotification,並且工作正常。

0

也許你可以嘗試使用「前臺服務」。要使用前臺服務,只需調用startForeground方法即可。

startForeground(NOTIFICATION_ID, notification); 

但是如果您不希望通知總是顯示在狀態欄上,您必須控制服務生命週期。希望這個答案對你有幫助。 :)