如何保持手机唤醒

手机的正常行为是闲置一段时间后屏幕变暗,然后熄灭,然后CPU关闭。

有些场景需要改变这种行为,例如播放视频时希望屏幕不要熄灭;

正在进行一些后台操作比如下载东西的时候希望CPU不要停止;


保持屏幕点亮:

在activity中执行如下code(不要在service或者其他组件调用)

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

这种做法不需要权限,一般你也无需clean这个flag,系统会管理一切。

或者在activity的layout中设置属性,这和上面的方法是一样的。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    ...
</RelativeLayout>


保持CPU打开

需要通过PowerManager拿到wake locks,这种方式一般不用再activity中,一般用在后台service中,用于在屏幕熄灭的时候让CPU继续开启。

首先需要声明权限<uses-permission android:name="android.permission.WAKE_LOCK" />

申请

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
Wakelock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        "MyWakelockTag");
wakeLock.acquire();

释放

wakeLock.release();


如果用法是你的broadcast receiver中启动一个service,这个service需要保持CPU开启,那么可以使用WakefulBroadcastReceiver

WakefulBroadcastReceiver会创建和管理一个PARTIAL_WAKE_LOCK,它保证启动的service执行期间CPU是开启的。

(这儿提到了PARTIAL_WAKE_LOCK,一共有4种lock。)

ValueCPUScreenKeyboard
PARTIAL_WAKE_LOCKOnOffOff
SCREEN_DIM_WAKE_LOCK OnDimOff
SCREEN_BRIGHT_WAKE_LOCKOnBrightOff
FULL_WAKE_LOCKObBrightBright

public class SimpleWakefulController extends Activity {
    Toast mToast;


    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.wakeful_alarm_controller);


        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.schedule);
        button.setOnClickListener(mScheduleListener);
    }


    private View.OnClickListener mScheduleListener = new View.OnClickListener() {
        public void onClick(View v) {
            // When the alarm goes off, we want to broadcast an Intent to our
            // BroadcastReceiver.  Here we make an Intent with an explicit class
            // name to have our own receiver (which has been published in
            // AndroidManifest.xml) instantiated and called, and then create an
            // IntentSender to have the intent executed as a broadcast.
            Intent intent = new Intent(SimpleWakefulController.this, SimpleWakefulReceiver.class);
            PendingIntent sender = PendingIntent.getBroadcast(SimpleWakefulController.this,
                    0, intent, 0);


            // We want the alarm to go off 30 seconds from now.
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND, 90);


            // Schedule the alarm!
            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);


            // Tell the user about what we did.
            if (mToast != null) {
                mToast.cancel();
            }
            mToast = Toast.makeText(SimpleWakefulController.this, R.string.simple_wakeful_scheduled,
                    Toast.LENGTH_LONG);
            mToast.show();
        }
    };
}


public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);


        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}


public class SimpleWakefulService extends IntentService {
    public SimpleWakefulService() {
        super("SimpleWakefulService");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        // At this point SimpleWakefulReceiver is still holding a wake lock
        // for us.  We can do whatever we need to here and then tell it that
        // it can release the wakelock.  This sample just does some slow work,
        // but more complicated implementations could take their own wake
        // lock here before releasing the receiver's.
        //
        // Note that when using this approach you should be aware that if your
        // service gets killed and restarted while in the middle of such work
        // (so the Intent gets re-delivered to perform the work again), it will
        // at that point no longer be holding a wake lock since we are depending
        // on SimpleWakefulReceiver to that for us.  If this is a concern, you can
        // acquire a separate wake lock here.
        for (int i=0; i<5; i++) {
            Log.i("SimpleWakefulReceiver", "Running service " + (i+1)
                    + "/5 @ " + SystemClock.elapsedRealtime());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }
        }
        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lyglostangel

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值