IntentService的StartForeground [英] StartForeground for IntentService
问题描述
我有一个IntentService
,我想通过正在进行的通知使其保持粘性.问题在于该通知出现,然后立即消失.该服务将继续运行.我应该如何在IntentService
中使用startForeground()
?
I have an IntentService
and I want to make it sticky with an ongoing notification. The problem is that the notification appears and then disappears immediately. The service continues to run. How should I use startForeground()
in an IntentService
?
@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
.按照书面规定,您的IntentService
会生存一毫秒左右.一旦返回onHandleIntent()
,该服务将被销毁.这应该是常规的Service
,您可以在其中派生自己的线程并管理线程和服务的生存期.
This should not be an IntentService
. As written, your IntentService
will live for a millisecond or so. Once onHandleIntent()
returns, the service is destroyed. This should be a regular Service
, where you fork your own thread and manage the lifetime of the thread and the service.
Notification
立即消失的原因是该服务立即消失.
The reason your Notification
is going away immediately is because the service is going away immediately.
这篇关于IntentService的StartForeground的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!