Android 为什么从异步后台服务回调创建时不显示我的通知?

Android 为什么从异步后台服务回调创建时不显示我的通知?,android,android-asynctask,android-service,android-notifications,android-background,Android,Android Asynctask,Android Service,Android Notifications,Android Background,我创建了一个服务,而不是intentservice,因为我需要做一些异步工作(位置+服务器调用),最后创建一个通知 我首先有一个创建通知的broadcastreceiver,仅此而已。那很好。但是,在服务中,我启动了一个locationmanager,然后在回调中启动了一个async,并且在该回调中尝试创建一个通知,它没有显示在抽屉中 这快把我逼疯了。正如你在代码中看到的那样,我试着干杯,这很有效我非常感谢您的帮助。 我的服务中的代码(为简洁起见简化了一点),其中一切正常,调用了服务器,记录了方

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

我首先有一个创建通知的broadcastreceiver,仅此而已。那很好。但是,在服务中,我启动了一个locationmanager,然后在回调中启动了一个async,并且在该回调中尝试创建一个通知,它没有显示在抽屉中

这快把我逼疯了。正如你在代码中看到的那样,我试着干杯,这很有效我非常感谢您的帮助。

我的服务中的代码(为简洁起见简化了一点),其中一切正常,调用了服务器,记录了方法等,但抽屉中没有显示任何通知(仅当我直接从onStartCommand调用cleanup时):


像manager.notify一样尝试(newrandom().nextInt(),notification);您每次都必须传递不同的通知Id,否则它将被旧Id替换

是的,但这正是我想要的。我的问题是根本不显示通知。同样,当我没有从异步回调创建通知时,这不是问题。在所有其他地方,“我的方法”调用都会生成一个已创建的通知。您确定正在调用
cleanup()
,并且该方法中没有引发异常吗?您应该添加调试日志,以确保实际调用了
manager.notify()
方法。是的,完成所有这些,谢谢。确实调用了清理,我在manager调用后有一个日志,上面写着“manager called”:
@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!
    }
}