Search code examples
javaandroidscheduletimertask

Android Start activity from timertask


Hi I have a timer task that check a file every 1 minute

public class MyTimerTask extends TimerTask {
//java.io.File file = new java.io.File("/mnt/sdcard/Bluetooth/1.txt");
java.io.File file = new java.io.File("init.rc");
public void CheckTheFile() 
{
if (file.exists())
    {   
    // I want here to start the Activity GetGPS
    }
}
@Override
public void run() {
    CheckTheFile();
}

}

in the check of file.exists , I want if the file is there , activity called GetGPS.
Thanks.


Solution

  • In your case I would recommend using Handler class. Here's what I would do:

    private static class PromoScroller implements Runnable {
    
        private Handler _scrollHandler;
    
        public PromoScroller(Handler scrollHandler) {
            _scrollHandler = scrollHandler;
        }
    
        @Override
        public void run() {
            // .. 
            _scrollHandler.sendEmptyMessage(0);
        }
    }
    

    // somewhere in your activity:

    _promoScroller = new PromoScroller(new Handler() {
            @Override
            public void dispatchMessage(Message msg) {
                super.dispatchMessage(msg);
                // !! catch message and start the activity
                Intent = new Intent(YourCurrentActivty.this, YourTargetActivity.class);
            }
        });
        _scrollerThread = new Thread(_promoScroller);
        _scrollerThread.start();
    

    P.S. those are bits of code I use for scrolling timer, but you get the idea

    UPD

    // TASK
    public class YourTimerTask extends TimerTask {
        private Handler _Handler;
    
        public YourTimerTask(Handler handler) {
            _Handler = handler;
        }
    
        public void run() {
            _Handler.sendEmptyMessage(0);
        }
    }
    
    // TASK HANDLER (private property in your acitivity)
    private Handler _taskHandler = new Handler(){
        public void dispatchMessage(android.os.Message msg) {
            // do cleanup, close db cursors, file handler, etc.
            // start your target activity
            Intent viewTargetActivity = new Intent(YourCurrentActivity.this, YourTargetActivity.class);
    
        };
    };
    
    
    // IN YOUR ACTIVITY (for isntance, in onResume method)
    Timer timer = new Timer();
    timer.schedule(new YourTimerTask(_taskHandler), seconds*1000);
    

    This should do the job. For timer - just google.timer example

    UPD2

    my mistake - it should be Handler _timerHandler = .... for starting activity look here