Android 停止启动\u粘性服务
当我按下“启动服务”时,我想创建一些在后台运行的应用程序,并在后台继续运行,即使该应用程序关闭或关闭。 为此,我使用START_STICKY,它可以工作,但问题是当我想终止服务时,应用程序关闭(如我所愿),然后我得到错误(不幸的是,进程服务已停止)。服务将尝试再次运行 我如何停止服务 p.S-I通过网络搜索解决方案,但没有成功 我的代码 主要活动Android 停止启动\u粘性服务,android,service,Android,Service,当我按下“启动服务”时,我想创建一些在后台运行的应用程序,并在后台继续运行,即使该应用程序关闭或关闭。 为此,我使用START_STICKY,它可以工作,但问题是当我想终止服务时,应用程序关闭(如我所愿),然后我得到错误(不幸的是,进程服务已停止)。服务将尝试再次运行 我如何停止服务 p.S-I通过网络搜索解决方案,但没有成功 我的代码 主要活动 public class MainActivity extends AppCompatActivity { private TextView
public class MainActivity extends AppCompatActivity {
private TextView textView;
private Intent i;
private static Button killSerBut;
private static final String TAG="com.example.elicahi.service";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView) findViewById(R.id.textView1);
killSerBut=(Button)findViewById(R.id.kill);
killSerBut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG,"onClick");
textView.setText("OnClick");
killServ();
}
});
//start the service
i= new Intent(this, MyService.class);
startService(i);
}
public void changeText(String msg)
{
textView.setText(msg);
}
public void killServ()
{
finish();
Log.d(TAG,"OnStop");
MyService myService=new MyService();
myService.stopService(i);
}
}
我的服务
public class MyService extends Service {
private static final String TAG="com.example.elicahi.service";
private Intent intent;
public MyService( ) {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand method called");
Runnable r= new Runnable() {
@Override
public void run() {
for (int i=0; i<10;i++){
long waitFor= System.currentTimeMillis()+1000;
while (System.currentTimeMillis()<waitFor){
synchronized (this){
try{
wait(waitFor-System.currentTimeMillis());
Log.d(TAG, "the service is doing something");
}catch (Exception e){}
}
}
}
}
};
//start the thread that inside the run nethod
Thread elichaiThread = new Thread(r);
elichaiThread.start();
//if the service is destroy- then restart it
return START_STICKY;
}
@Override
public void onDestroy() {
Log.d(TAG,"onDestroy method called");
stopSelf();
}
/* public void killServ(Intent intGet)
{
Log.d(TAG,"Killed");
intent=intGet;
}*/
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
}
使用清单文件中
服务
标记下的属性
android:stopWithTask="true"
请替换此方法
public void killServ()
{
stopService(MainActivity.this,MyService.class);
}
这是事件的完整日志吗?是的,那么日志中的错误在哪里?我不知道。我猜这个错误是由于终止服务而发生的……但是主要的问题是服务启动得很快,这是因为您有
start\u STICKY
-使用:start\u NOT\u STICKY
-将此代码stopService(新的意图(这个,MySerivce.class))代码>在活动的ondestory()方法中。我添加了。服务仍然重新启动以获取错误。stopService只有一个parm>stopService(意图)…请尝试此stopService(新意图(MainActivity.this,MyService.class));
android:stopWithTask="true"
public void killServ()
{
stopService(MainActivity.this,MyService.class);
}