how to wakeup android phone from sleep?

前端 未结 3 1273
情深已故
情深已故 2021-02-20 14:16

How to wakeup android phone from sleep (suspend to mem) programmably? I don\'t want to acquire any wakelock, which means the phone goes into \"real\" sleep with the cpu disabled

3条回答
  •  没有蜡笔的小新
    2021-02-20 14:59

    I just wrote an application which can do this, here is some example code: First, I create an AlarmManager and set an alarm for a specific time:

    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 15);
    calendar.set(Calendar.MINUTE, 30);
    calendar.set(Calendar.SECOND, 0);
    // if the time is before now then add one day to it
    if(calendar.getTimeInMillis() < System.currentTimeMillis())
       calendar.setTimeInMillis(calendar.getTimeInMillis()+86400000);
    manager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 0);
    

    I need a BroadcastReciever to recieve this alarm. For this I have to put into my manifest:

    
        
    ...
    
    

    and I also have the AlarmReciever class, which starts my main Activity on recieve:

    public class AlarmReceiver extends BroadcastReceiver {
        public static final String WAKE = "Wake up";
        @Override
        public void onReceive(Context context, Intent intent) {
            //Starting MainActivity
            Intent myAct = new Intent(context, MainActivity.class);
            myAct.putExtra(WAKE, true);
            myAct.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(myAct);
        }
    }
    

    and in my Activity's onCreate function I have:

    // Wake up phone if needed
    if(getIntent().hasExtra(AlarmReceiver.WAKE) && getIntent().getExtras().getBoolean(AlarmReceiver.WAKE)){
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
                            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
                            WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
                            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    }
    

    This code wakes up my phone at next 15:30:00 (either it is today or tomorrow).

提交回复
热议问题