Android - 如何确保我的服务已重新启动?
我有一个带有后台运行服务的 Android 应用程序。
当服务崩溃或被 Android 杀死时,我可以看到 Android 尝试再次重新启动它。
然而,该服务从未真正重新启动,我可以看到 Android 安排重新启动,但它实际上发生了。
我的代码如下:
@Override
public void onCreate() {
String ns = Context.NOTIFICATION_SERVICE;
mNotificationManager = (NotificationManager) getSystemService(ns);
mTelephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
audio_service = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
handleCommand(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
void handleCommand(Intent intent) {
running = true;
mTelephonyManager.listen(new IncomingListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
我的代码中是否缺少某些内容以允许重新启动服务?
I have an Android application with a background running Service.
When the Service crashes or gets killed by Android I can see that Android tries to restart it again.
However the Service never actually restarts, I can see Android scheduling the restart but it new actually happens.
My code is as follows:
@Override
public void onCreate() {
String ns = Context.NOTIFICATION_SERVICE;
mNotificationManager = (NotificationManager) getSystemService(ns);
mTelephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
audio_service = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
handleCommand(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
void handleCommand(Intent intent) {
running = true;
mTelephonyManager.listen(new IncomingListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
Is there something missing in my code to allow the Service be restarted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试过使用 <代码>startForeground()?
Have you tried using
startForeground()
?