I want to run the given below piece of code repetitively after two seconds, I searched for the solutions many times and find this one.
The code given below is working only for sometime because Timer is destroyed by system after sometime. I also tried Alarm Manager which starts the service after 2 seconds but consumes too much memory even if the service doesn't contain any code.
Please( its been 3 continous days googling for the solution), suggest some other way to run that bunch of code repetitively in background every 2 second without being destroyed by the system.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
final ActivityManager.RunningAppProcessInfo appProcess =runningAppProcessInfo.get(0) ;
currentAppName = appProcess.processName.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
if(temp.equalsIgnoreCase(currentAppName))
{
}
else
{ Toast.makeText(MyService.this.getApplicationContext(),appProcess.processName.toString(),Toast.LENGTH_SHORT).show();
temp=""+currentAppName;
}
}
});
for(int i=0;i<LockedApps.LockedAppsList.size();i++) {
if (appProcess.processName.toString().contains(LockedApps.preflist.get(i))) {
if (flag == 0) {
Intent x = new Intent(getApplicationContext(), LockActivity.class);
x.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(x);
}
}
}