您的位置:首页 > 其它

如何让手机保持唤醒状态

2013-12-08 11:35 190 查看
手机的正常行为是闲置一段时间后屏幕变暗,然后熄灭,然后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 MyWakefulReceiver extends WakefulBroadcastReceiver
{

    @Override

    public void onReceive(Context context, Intent intent) {

        // Start the service, keeping the device awake while the service is

        // launching. This is the Intent to deliver to the service.

        Intent service = new Intent(context, MyIntentService.class);

        startWakefulService(context, service); //用startWakefulService启动service

    }

}

在service端执行完成后要call completeWakefulIntent释放wake lock

    protected void onHandleIntent(Intent intent) {

        Bundle extras = intent.getExtras();

        // Do the work that requires your app to keep the CPU running.

        // ...

        // Release the wake lock provided by the WakefulBroadcastReceiver.

        MyWakefulReceiver.completeWakefulIntent(intent); //这个intent和传入的intent是一摸一样的。

    }

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: