How to run a Runnable thread in Android at defined intervals?

后端 未结 11 1983
青春惊慌失措
青春惊慌失措 2020-11-22 02:50

I developed an application to display some text at defined intervals in the Android emulator screen. I am using the Handler class. Here is a snippet from my cod

11条回答
  •  忘了有多久
    2020-11-22 03:18

    An interesting example is you can continuously see a counter/stop-watch running in separate thread. Also showing GPS-Location. While main activity User Interface Thread is already there.

    Excerpt:

    try {    
        cnt++; scnt++;
        now=System.currentTimeMillis();
        r=rand.nextInt(6); r++;    
        loc=lm.getLastKnownLocation(best);    
    
        if(loc!=null) { 
            lat=loc.getLatitude();
            lng=loc.getLongitude(); 
        }    
    
        Thread.sleep(100); 
        handler.sendMessage(handler.obtainMessage());
    } catch (InterruptedException e) {   
        Toast.makeText(this, "Error="+e.toString(), Toast.LENGTH_LONG).show();
    }
    

    To look at code see here:

    Thread example displaying GPS Location and Current Time runnable alongside main-activity's User Interface Thread

提交回复
热议问题