Android服务需要始终运行(永不暂停或停止)

我创建了一个服务,希望一直运行此服务,直到我的手机重新启动或强制关闭为止。该服务应在后台运行。


创建的服务和启动服务的示例代码:


启动服务:


Intent service = new Intent(getApplicationContext(), MyService.class);

getApplicationContext().startService(service);

服务:


public class MyService extends Service {


    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        // TODO do something useful

        HFLAG = true;

        //smsHandler.sendEmptyMessageDelayed(DISPLAY_DATA, 1000);

        return Service.START_NOT_STICKY;

    }


    @Override

    public IBinder onBind(Intent intent) {

        // TODO for communication return IBinder implementation

        return null;

    }

}

清单声明:


<service

    android:name=".MyService"

    android:icon="@drawable/ic_launcher"

    android:label="@string/app_name" >

</service>

是否可以始终在应用程序暂停或其他任何情况下运行此服务。一段时间后,我的应用程序暂停,服务也暂停或停止。因此,如何在后台始终运行此服务。


温温酱
浏览 1022回答 3
3回答

慕的地10843

如果您已经有了一项服务,并且希望它一直运行,那么您需要添加两件事:在服务本身中:public int onStartCommand(Intent intent, int flags, int startId) {&nbsp; &nbsp; return START_STICKY;}在清单中:android:launchMode="singleTop"除非您在服务中需要绑定,否则无需添加绑定。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java
Android