我试图停止我的服务,即使我的 destroy 方法也已执行但我的服务没有停止。我已经尽力了。请帮帮我。
我的代码如下:
MainActivity
Intent intent = new Intent(this,Myservice.class);
startService(意向); //在开始按钮中。
Intent intent = new Intent(this,Myservice.class);
stopService(意向); //在停止按钮。
MYSERVICE
public class Myservice extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"runing",Toast.LENGTH_LONG).show();
{
myTherad th=new myTherad();
Thread thread=new Thread(th);
thread.start();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Toast.makeText(this,"stop",Toast.LENGTH_LONG).show();
super.onDestroy();
}
class myTherad implements Runnable {
@Override
public void run() {
synchronized (this)
{
try {
for(int i=0;i<10;i++)
{
wait(1000);
Log.d("mfnhsdgjkfn","===="+String.valueOf(i));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stopSelf();
}
}
}
答案 0 :(得分:0)
我认为您的服务已停止,但不是Thread
。通过引入以下内容,在onDestroy
您的服务中取消您的主题某种状态变量:
class myTherad implements Runnable {
// Indicates that the runnable should stop.
private boolean shouldStop = false;
@Override
public void run() {
synchronized (this)
{
try {
for(int i=0;i<10 && !shouldStop;i++)
{
wait(1000);
Log.d("mfnhsdgjkfn","===="+String.valueOf(i));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stopSelf();
}
并将runnable声明为class属性:
private myTherad runnable;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
runnable=new myTherad();
Thread thread=new Thread(runnable);
thread.start();
return super.onStartCommand(intent, flags, startId);
}
并停止onDestroy
中的runnable:
@Override
public void onDestroy() {
Toast.makeText(this,"stop",Toast.LENGTH_LONG).show();
runnable.shouldStop = true;
super.onDestroy();
}
至少在执行最新的wait
之后,您的线程应该停止。你可以通过中断来优化它。
答案 1 :(得分:0)
我们必须使用正在运行的线程,thread.interrupt()
将执行此操作并提供java.lang.InterruptedException
,请尝试以下代码:
public class MyService extends Service {
public MyService() {}
myTherad th;
Thread thread;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"runing",Toast.LENGTH_LONG).show();
{
th=new myTherad();
thread=new Thread(th);
thread.start();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this,"stop",Toast.LENGTH_LONG).show();
thread.interrupt();
}
class myTherad implements Runnable {
@Override
public void run() {
synchronized (this)
{
try {
for(int i=0;i<10;i++)
{
wait(1000);
Log.d("LOG","===="+String.valueOf(i));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stopSelf();
}
}
}