我创建了一个Service,而不是intentservice,因为我需要做一些异步的东西(位置+服务器调用),最后创建一个Notification。
我首先有一个创建通知的广播接收器,仅此而已。这很好。但是,在服务中我启动一个位置管理器,然后在回调中启动一个异步,并在THAT回调中尝试创建一个通知,它不会显示在抽屉中!
这让我发疯了。我尝试了在代码中看到的吐司,并且有效...... 我真的很感激帮助。我的服务中的代码(为简洁起见,简化了一点)如果一切正常,调用服务器,记录方法等,但抽屉中出现NO Notification(仅当我直接从onStartCommand调用cleanup时):
@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!
}
}
答案 0 :(得分:0)
尝试像manager.notify( new Random()。nextInt(),通知);每次都必须传递不同的通知ID,否则它将被旧的通知ID替换