简体   繁体   中英

Android app don't work in sleep mode

I have app with timer. When I press the power button, my app going to sleep mode and stopped timer. What should I do to timer continue to working. Below my very simple code timer.

Thread t = new Thread(){
    @Override
    public void run() {
        while (!isInterrupted()){
            try {
                Thread.sleep(1000);
                i++;
                Log.e("pokaz "," i "+i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
};

I solved my problem. I write this code in activity

PowerManager pm;
    PowerManager.WakeLock wl;
    pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
    wl.acquire();

and layout write this code

android:keepScreenOn="true"

but now my application is in background and version API is kitkat evrything is ok. When test my aplication in API lolipop and goes on sleep mode and next turn on phone I see message "unfortunately myApp has stopped". Why?

To work your app in background you need to use Service , IntentService or BroadCastReceiver .

And do your thread work inside Service .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM