P.Carlino P.Carlino - 27 days ago 9
Android Question

Service with loop freze the activity

I have a activity that call startService(intent) and this one in his method onStatCommand() create a thread that checks the running app every second.
The problem is that the thread freze the creation of the activity and the screen show only a white screen. If i delete the for(;;) statment in the thread it works. why?

here there is the onStartCommand() code:

@Override
public int onStartCommand(Intent intent,int flags,int startid)
{
super.onStartCommand(intent,flags,startid);


final Thread thread= new Thread(){
@Override
public void run()
{
Context context = getApplicationContext();
for(;;) {
long current = System.currentTimeMillis();
UsageStatsManager usageStatsManager = ((UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE));
for (UsageStats usageStats : usageStatsManager.queryAndAggregateUsageStats( current - 1000*2, current).values()) {
Log.i("Path changed name",usageStats.getPackageName());

if(usageStats.getPackageName()=="com.android.chrome")
{
Log.i("Path name",usageStats.getPackageName());
stopSelf();
break;
}
}
try {
currentThread().sleep(1000);
}catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
thread.run();;
return 0;

}

Answer

There is problem with Thread code, You should call Start method to start a new Thread not run.

Problem code:

thread.run();

Fixed code:

thread.start();
Comments