使用 stopService() 时无法停止Service
使用unbindService() 时 ,会关闭应用程序,再停止Service (不是我要的)。
我需要的效果:应用程序存在且能够关闭Service
需要的效果是 :
点击 RadioButton(开启服务)在后台一直运行即使应用关闭
点击 RadioButton(关闭服务)无论应用是否停止、关闭。Service关闭
activity 通过bindservice 与这个services进行绑定后,activity 可以获取 services 中的返回的内部类Binder 对象,该Binder implement必须实现一个自己定义的接口(方法),然后这个方法在services中具体实现为stopself(),这样就可以让ativity通过binder调用自己定义的接口(方法)控制service 关闭
和activity(fragment)的生命周期绑定,在ondestroy中stopself() 试试呢!或者在activity的ondestroy方法中调用stopService(intent)
试了,没有停止Service
如果用startservice开启地服务,使用stopservice就可关闭服务;
如果用bindservice绑定地服务,使用unbindservice就可以关闭服务;
如果同时使用了二者,则需要使用stopservice和unbindservice才能关闭服务,service的onDestory才能执行。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int id = START_STICKY_COMPATIBILITY;
return super.onStartCommand(intent, flags, id);
}
startId默认返回START_STICKY,即Service被杀死之后,马上创建新的。改一下ID即可解决你的问题。
menifest.xml里设置成系统级别的,即时程序关掉了服务还在运行
xml
<service
android:name="com.example.service.MyService"
android:enabled="true"
android:process="system" />
java
Intent startIntent = new Intent(this, MyService.class);
startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(startIntent);
java
public class MyService extends Service {
boolean running = false;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
running = true;
Log.i("trans", "onStartCommand");
new Thread() {
public void run() {
try {
while (running) {
Thread.sleep(1000);
Log.i("trans", "do");
}
} catch (Exception e) {
}
};
}.start();
return START_STICKY;
}
@Override
public void onDestroy() {
Log.i("trans", "onDestroy");
running = false;
super.onDestroy();
}
}
stopService的时候如果有其他的上下文环境也在与该Service做交互,那么该service只不会进行onDestory。
想控制service里面程序执行的开始和暂停,不用一定非要关闭service,通过给Service传递参数让其停止就行。
现在这招还管用吗?能顾保证退出界面后服务还运行吗?我使用华为手机,当app退出后,息屏之后服务就被杀死。
@Override
public void onDestroy() {
super.onDestroy();
if (mFloatLayout != null) {
mWindowManager.removeView(mFloatLayout);
}
}
重写onDestroy()方法试下。实测 服务里注释掉之后,无论是stopService还是stopSelf都不能停止服务
把线程布局广播在onDestroy方法中自行销毁
新建全局变量
public class MyClass{
public static boolean isServiceRun = false;
...
}
在startService时设置其值为true
再在Service运行代码中加入判断,如果非真则stopSelf。
在Service外,如果要停止Service只需调用 MyClass.isServiceRun = false; 即可。
// 以下仅供参考
public int onStartCommand(Intent intent, int flags, int startId){
new Thread(new Runnable() {
@Override
public void run() {
while (MyClass.isServiceRun) {
}
stopSelf();
}
}).start();
}