为什么从异步背景服务回调创建时未显示我的通知



我已经创建了一个服务,而不是意图服务,因为我需要做一些异步工作(位置 服务器调用(,最后创建通知。

我首先有一个创建通知的广播员,仅此而已。效果很好。但是,在服务中,我启动了一个位置管理器,然后在回调中启动异步,然后在该回调中尝试创建通知,在抽屉中未显示!

这让我发疯。我尝试了您在代码中可以看到的吐司,这有效... 我真的很感谢您的帮助。

我的服务中的代码(简化为简短(,在所有功能正常,服务器,方法已记录等,但在抽屉中没有通知(仅当我直接从OnstartCommand调用清理(中没有通知(:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand");
    //.... doing various other stuff
    handleAsyncStuff(session);
    return START_STICKY;
}
....in my callback from final async server rest call:

private void cleanup(String header, String message){
    try{
        Log.d(TAG, "cleanup;header;" + header + ";message;" + message);
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(getApplicationContext(), message, duration);
        toast.show();
        Intent notificationIntent = new Intent(getApplicationContext(), MainTabActivity.class);
    notificationIntent.putExtra(PreferencesHandler.INTENT_HEADER_PARAM, header);        notificationIntent.putExtra(PreferencesHandler.INTENT_MESSAGE_PARAM, message);
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
    builder.setContentTitle(header)
        .setAutoCancel(true)
        .setWhen(System.currentTimeMillis())         
        .setContentText(message)
        .setSmallIcon(R.drawable.notification)
        .setAutoCancel(true)
        .setDefaults(Notification.DEFAULT_ALL);
    PendingIntent pendingIntent = PendingIntent.getActivity(GeofenceBackgroundService.this.getApplicationContext(),
        NOTIFICATION_ID,
        notificationIntent,
        PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);
    Notification notification = builder.build();
    NotificationManager manager = (NotificationManager)     getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(NOTIFICATION_ID, notification);
    }finally{
        //stopSelf(); Comment out did not make notification appear!
    }
}

试试它,例如manager.notify( new andural((。nextint((,notification(;您必须每次传递不同的通知ID,否则它将被旧一个

替换

最新更新