You should use Handler for that. Use it like
android.os.Handler handler = new android.os.Handler(); //declear them globly
Runnable runnable=null;
Initialize Runnable inside onCreate() like
runnable = new Runnable() {
@Override
public void run() {
finish();
}
};
Copy these two methods in your code
void start() {
handler.postDelayed(runnable, TimeUnit.MINUTES.toMillis(15));
}
void stop(){
handler.removeCallbacks(runnable);
}
Override onUserInteraction() method of Activityand call start() and stop()
@Override
public void onUserInteraction() {
super.onUserInteraction();
stop();
start();
}
Don't forget to call start() method from onCreate() too after the runnable initialization.
Its run() method will call just after 15 minutes after user inactive, do your task there(you want to finish that Activity or something else)
//////////=====Updated=====\\\\\\\\\
Paste this BaseActivity in your code
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.util.concurrent.TimeUnit;
public class BaseActivity extends AppCompatActivity {
private static android.os.Handler handler = new android.os.Handler();
private static Runnable runnable = null;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (handler == null) {
handler = new Handler();
} else {
handler.removeCallbacks(runnable);
}
if (runnable == null)
runnable = new Runnable() {
@Override
public void run() {
//do your task here
}
};
start();
}
@Override
public void onUserInteraction() {
super.onUserInteraction();
stop();
start();
}
void start() {
handler.postDelayed(runnable, TimeUnit.MINUTES.toMillis(15));
}
void stop() {
handler.removeCallbacks(runnable);
}
}
Now extends BaseActivity from all of your Activity except AppCompatActivity or else, like this.
public class HomeActivity extends BaseActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
}
Do you task inside run() method, I suggest you to start another Activity and clear activity stack from run() method, because finish() will work there only for 1 Activity.