我创建了一个服务,希望一直运行此服务,直到我的手机重新启动或强制关闭为止。该服务应在后台运行。创建的服务和启动服务的示例代码:启动服务: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>是否可以始终在应用程序暂停或其他任何情况下运行此服务。一段时间后,我的应用程序暂停,服务也暂停或停止。因此,如何在后台始终运行此服务。
3 回答

慕的地10843
TA贡献1785条经验 获得超8个赞
如果您已经有了一项服务,并且希望它一直运行,那么您需要添加两件事:
在服务本身中:
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
在清单中:
android:launchMode="singleTop"
除非您在服务中需要绑定,否则无需添加绑定。
添加回答
举报
0/150
提交
取消