android-如何自行停止服务?
我在活动中启动服务,然后希望该服务在一段时间后自行停止。
我在服务中调用了stopSelf(),但是它不起作用。
如何使服务自行停止?
说“不起作用”,我想您的意思是未调用该服务的onDestroy()
方法。
我遇到了同样的问题,因为我使用标志BIND_AUTO_CREATE将某些ServiceConnection绑定到服务本身。这将使服务保持活动状态,直到每个连接都解除绑定。
一旦更改为不使用标志(零),就可以自行终止服务(stopSelf()
)。
示例代码:
final Context appContext = context.getApplicationContext();
final Intent intent = new Intent(appContext, MusicService.class);
appContext.startService(intent);
ServiceConnection connection = new ServiceConnection() {
// ...
};
appContext.bindService(intent, connection, 0);
终止服务(不是进程):
this.stopSelf();
希望能有所帮助。
通过拨打stopSelf()
,服务停止。
请确保没有线程在后台运行,这会使您感到该服务尚未停止。
在线程中添加打印语句。
希望这可以帮助。
由于您没有发布代码,所以我不知道您在做什么,但是您必须声明要停止的内容:
this.stopSelf();
如:
public class BatchUploadGpsData extends Service {
@Override
public void onCreate() {
Log.d("testingStopSelf", "here i am, rockin like a hurricane. onCreate service");
this.stopSelf();
}
如果“不起作用”表示您的进程没有被杀死,那么这就是android的工作方式。 System.exit(0)
或Process.killProcess(Process.myPid())
将终止您的进程。 但这不是Android的处理方式。
高温超导
stopForeground(true);
stopSelf();
使用stopSelf()从自身停止服务。
我只是遇到了同样的问题。 就我而言,我有一个单例服务管理器,用于与该服务进行通信。 在管理器中,服务是这样启动的:
context.bindService(new Intent(context, MyService.class), serviceConnection, Context.BIND_AUTO_CREATE);
通过按照Alik Elzin的建议删除Context.BIND_AUTO_CREATE,我已经能够使用this.stopSelf()停止服务,并在执行此操作时调用了onDestroy()。 问题是在那之后,我无法使用上面的命令从管理器中重新启动服务。
最后,我通过使用服务中的回调(告诉管理器停止该服务)来解决此问题。 这样,在启动/停止服务时,经理总是负责任,一切似乎都很好。 我不知道这样做是否有任何反指示。
代码真的很简单。 在服务中创建一个回调,并在连接类中在管理器中进行设置:
private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
myService = ((MyService.LocalBinder)service).getService();
myService.setCallback(new MyService.MyServiceCallback() {
@Override
public void onStop() {
stopService();
}
});
}
public void onServiceDisconnected(ComponentName className) {
myService = null;
}
};
并停止服务:
public void stopService()
{
if(mServiceConnection != null){
try {
mContext.unbindService(mServiceConnection);
} catch (Exception e) {}
}
mContext.stopService(new Intent(mContext, BleDiscoveryService.class));
}
在服务中,只需在需要停止时调用myCallback.onStop()。
这里没有提到的另一个肮脏的技巧是抛出像NPE这样的异常。 有一天,我需要停止InputMethodService,这一技巧很有用。
为了让您的服务停止运行..创建BroadcastReceiver
类。.在您的服务中,像这样呼叫接收者。
服役中
sendBroadcast(new Intent("MyReceiver"));
在广播接收器中
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.stopService(new Intent(context,NotificationService.class));
}
}
清单文件
<receiver
android:name="MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="MyReceiver"/>
</intent-filter>
</receiver>
如果您在服务中使用单独的Thread
,则在通过致电stopSelf()
或stopService()
停止服务后,Thread
会继续运行。 如果您要停止Thread
,则应致电Thread
中的Thread.interrupted()
(如果Thread
正在睡眠,则可能会导致Exception
)