我有一个IntentService
,我想使用正在运行的通知使其保持黏性。问题是通知会出现然后立即消失。服务仍在继续运行。我应该如何在IntentService
中使用startForeground()
?
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Notification notification = new Notification(R.drawable.marker, "Notification service is running",
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, DashboardActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "App",
"Notification service is running", pendingIntent);
notification.flags|=Notification.FLAG_NO_CLEAR;
startForeground(1337, notification);
return START_STICKY;
}
@Override
protected void onHandleIntent(Intent intent) {
String id = intent.getStringExtra(ID);
WebSocketConnectConfig config = new WebSocketConnectConfig();
try {
config.setUrl(new URI("ws://" + App.NET_ADDRESS
+ "/App/socket?id="+id));
} catch (URISyntaxException e) {
e.printStackTrace();
}
ws = SimpleSocketFactory.create(config, this);
ws.open();
}
谢谢
IntentService
只会存在一毫秒左右的时间,因为在onHandleIntent()
中的代码只需要一毫秒左右的运行时间。 - CommonsWareonHandleIntent
方法中没有任何线程阻塞的代码来防止IntentService
销毁。 - Arcao该方法可能需要几秒钟才能完成,所以应该只能从一个工作线程中调用。
- sam_k