Seems that stop()
is not needed to fix the issue. I would suggest to do it like the following:
public class Waiter extends Thread {
private static final String TAG=Waiter.class.getName();
private long lastUsed;
private long period;
private boolean stop;
private final WeakReference<Context> mContextRef;
public Waiter(final long period, final Context context) {
this.period = period;
stop = false;
mContextRef = new WeakReference<Context>(context);
}
public void run() {
long idle = 0;
this.touch();
do {
idle = System.currentTimeMillis()-lastUsed;
Log.d(TAG, "Application is idle for " + idle + " ms");
try {
Thread.sleep(5000); //check every 5 seconds
if(idle > period) {
final Context context = mContextRef.get();
if (context != null) {
// start activity
startActivity(context);
}
stop = true;
}
}
catch (InterruptedException e) {
Log.d(TAG, "Waiter interrupted!");
// set stop, because smb has called interrupt() on the thread
stop = true;
}
}
while(!stop);
Log.d(TAG, "Finishing Waiter thread");
}
private void startActivity(final Context context) {
final Intent intent = new Intent(context, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
// If there is nothing that can send a text/html MIME type
e.printStackTrace();
}
}
public synchronized void touch() {
lastUsed=System.currentTimeMillis();
}
public synchronized void setPeriod(long period) {
this.period=period;
}
}
So, it'll be one-shot thread (once idle timeout, You'll need to create new one) which You'll be able to stop any time by just using standard API Thread.interrupt().