How to keep active a runnable thread when an activ

2019-08-28 05:09发布

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?

1条回答
太酷不给撩
2楼-- · 2019-08-28 05:26

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" />

Start and stop your service with

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;

}

查看更多
登录 后发表回答