2016-08-19 116 views
1

面對Android棒棒糖顯示通知的問題。當應用程序打開時,通知顯示應用程序正常,但是當應用程序關閉時,它們不會顯示。在Android的4倍版本中,一切正常。這裏有一個方法來顯示他們android棒棒糖。通知不起作用

@TargetApi(Build.VERSION_CODES.LOLLIPOP) 
    private void sendNotification(String body, String title, String badge) { 
     Intent intent = new Intent(this, MainActivity.class); 
     intent.putExtra("from_notify", true); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, Integer.valueOf(badge), intent, 
       PendingIntent.FLAG_ONE_SHOT); 

     Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.drawable.ic_stat_name) 
       .setContentTitle(title) 
       .setContentText(body) 
       .setPriority(Notification.PRIORITY_HIGH) 
       .setShowWhen(true) 
       .setVisibility(Notification.VISIBILITY_PUBLIC) 
       .setAutoCancel(true) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent); 

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

     notificationManager.notify(0, notificationBuilder.build()); 
    } 
+0

我檢查了我的棒棒糖設備上的代碼,它工作得很好。在活動和廣播接收器兩種情況下進行測試。爲了確保活動已經結束,接收器響應BOOT動作。所以問題在別處。請問您的測試設備的製造商是什麼?一些製造商進行了一些額外的「應用程序優化」。例如華爲,它強制停止你的應用程序,所以沒有廣播接收器將工作,這將符合描述的行爲。請記住,「強制停止」會禁用您的應用程序,直到從啓動器重新啓動。 – mhenryk

回答

0

,我認爲這就是問題所在:

當你的應用程序被關閉,所有的應用程序的數據將包括通知和靜態數據被清除,所以,如果你想通知一直存在,您必須從服務中發送它(創建服務類並在後臺運行它)。

試試這個:

public class YourService extends Service { 
@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    //send your notifications here 
    return START_STICKY; 
} 
@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 
} 

請注意,您可以從其他類不只是從服務類發送通知,但你必須在後臺運行一個服務,因爲它有助於保持靜態數據的應用程序後,它是封閉的,這對我有效。

我希望這會幫助你。

+0

這是不正確的。只有正在進行的通知需要服務支持。像問題中的定期通知可以從任何地方發起。 – mhenryk

+0

只是我告訴過你(我想),我沒有和lolipop一起工作,我希望你很快找到答案,祝你好運。 – phoenix