如何在活动关闭时保持可运行线程的活动状态,但在活动再次启动时销毁线程 [英] How to keep active a runnable thread when an activity is closed but destroy the thread when the activity start again

查看:64
本文介绍了如何在活动关闭时保持可运行线程的活动状态,但在活动再次启动时销毁线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的其中一项活动中有一个可运行线程,该线程在活动开始时启动.即使我的活动完成,我也想保持线程运行,并且我想在同一个活动再次开始时销毁线程.这是可能的,还是我必须尝试新的方法来实现我的目标?

I have a runnable thread in one of my activities, which starts when the activity starts. I want to keep the thread running even when my activity is finished, and I want to destroy the thread when the same activity starts again. Is this possible or do I have to try new approach to achieve my goal?

推荐答案

我建议使用服务.他们活得如你所愿

I would suggest using a service. They live as long as you want them to

public class MyService extends Service {
private static final String TAG = "MyService";

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

}

@Override
public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    //stop thread
}

@Override
public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onStart");
    //start thread (again)
}

}

您必须在清单中声明您的服务

You have to declare your service in your manifest

<service android:enabled="true" android:name=".MyService" />

使用

startService(new Intent(this, MyService.class));
stopService(new Intent(this, MyService.class));

如果您想检查您的服务是否正在运行,您可以使用此代码

If you want to check if your service is running you can use this code

private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
    if (MyService.class.getName().equals(service.service.getClassName())) {
        return true;
    }
}
return false;

}

这篇关于如何在活动关闭时保持可运行线程的活动状态,但在活动再次启动时销毁线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆