【发布时间】:2017-03-27 14:51:14
【问题描述】:
我已经搜索并找到了与标题相似的问题,但到目前为止还没有解决方案。 我有以下服务
public class MyService extends Service {
public MyService() {
}
private static final String TAG =
"ServiceExample";
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand " + startId);
final int currentId = startId;
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 3; i++)
{
long endTime = System.currentTimeMillis() +
10*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime -
System.currentTimeMillis());
} catch (Exception e) {
}
}
}
Log.i(TAG, "Service running " + currentId);
}
//stopSelf();
}
};
Thread t = new Thread(r);
t.start();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "Service onBind");
return null;
}
@Override
public void onDestroy() {
Log.i(TAG, "Service onDestroy");
super.onDestroy();
//Log.i(TAG, "Service Destroyed");
}
}
这是从我的活动中调用的,该活动有两个按钮:一个用于启动服务,一个用于停止服务
public class ServiceExampleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_example);
}
public void buttonClick(View view)
{
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
public void stopClick(View view)
{
Intent intent = new Intent(this, MyService.class);
stopService(intent);
}
}
但是这不起作用。服务没有停止。 奇怪的是调用了 onDestroy 函数,但之后 runnable 仍在运行。 如何停止服务?
==============================================
编辑:我终于通过以下更改实现了它: 在 onDestroy 函数中
@Override
public void onDestroy() {
Log.i(TAG, "Service onDestroy");
// mHandler.removeCallbacks(r);
t.interrupt();
super.onDestroy();
//Log.i(TAG, "Service Destroyed");
}
线程 t 必须是类成员(在它在 onStartCommand 中声明之前),我将可运行对象修改为 this
r = new Runnable() {
public void run() {
for (int i = 0; i < 3; i++)
{
long endTime = System.currentTimeMillis() +
10*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime -
System.currentTimeMillis());
} catch (Exception e) {
return; //HERE to detect if the thread has been interrupted
}
}
}
Log.i(TAG, "Service running " + currentId);
}
stopSelf();//I have to use this otherwise it doesn't stop
}
};
我想知道为什么通常我必须使用 stopSelf 但被打断时就没有必要了。我想 stopSelf 只是调用 onDestroy
【问题讨论】: