Android - 如何确保我的服务重新启动? [英] Android - how to make sure my Service is restarted?

查看:230
本文介绍了Android - 如何确保我的服务重新启动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有后台运行服务的Android应用程序。



当服务崩溃或被Android杀死时,我可以看到Android尝试重新启动它。 / p>

但是,服务从未真正重新启动,我可以看到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);


}

//这是旧的onStart方法,将在2.0之前的
//平台上调用。在2.0或更高版本上,我们重写onStartCommand(),所以这个
//方法不会被调用。
@Override
public void onStart(Intent intent,int startId){
handleCommand(intent);
}

@Override
public int onStartCommand(Intent intent,int flags,int startId){
handleCommand(intent);
//我们希望此服务继续运行,直到显式
//停止,因此返回sticky。
return START_STICKY;
}

void handleCommand(Intent intent){

running = true;
mTelephonyManager.listen(new IncomingListener(),PhoneStateListener.LISTEN_CALL_STATE);

}






解决方案

您是否尝试过使用 startForeground )



http://developer.android.com/intl/de/reference/android/app/Service.html#startForeground%28int ,%20android.app.Notification%29


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?

解决方案

Have you tried using startForeground()?

http://developer.android.com/intl/de/reference/android/app/Service.html#startForeground%28int,%20android.app.Notification%29

这篇关于Android - 如何确保我的服务重新启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆