1

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;

}
P.Carlino
  • 661
  • 5
  • 21
  • 2
    Possible duplicate of [What's the difference between Thread start() and Runnable run()](http://stackoverflow.com/questions/8579657/whats-the-difference-between-thread-start-and-runnable-run) – Mike M. Nov 06 '16 at 09:27
  • run() calls the runnable in the current thread which is the UI thread, and you are sleeping it for 1 sec, that's why the screen freezes – Binary Baba Nov 06 '16 at 09:34

1 Answers1

4

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();
Saurabh Khare
  • 1,227
  • 13
  • 24