Android通过广播实现灭屏和唤醒

时间:2021-08-23 14:35:07

1、要实现灭屏和唤醒,需要在Manifest文件添加如下权限:

    <!-- 屏幕唤醒 -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <!-- 屏幕熄灭 -->
    <user-permission android:name="android.permission.DEVICE_POWER" />

2、以下是封装的一个工具类,实现屏幕唤醒和熄灭


package testWakeAndLock;

import android.content.Context;
import android.os.PowerManager;
import android.os.SystemClock;

import com.example.testshellcmd.SharedApplication;

public class WakeAndLock {
	Context context;
	PowerManager pm;
	PowerManager.WakeLock wakeLock;

	public WakeAndLock() {
		context = SharedApplication.context;
		pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
				| PowerManager.SCREEN_DIM_WAKE_LOCK, "WakeAndLock");
	}

	/**
	 * 唤醒屏幕
	 */
	public void screenOn() {
		wakeLock.acquire();
		android.util.Log.i("cxq", "screenOn");

	}

	/**
	 * 熄灭屏幕
	 */
	public void screenOff() {
		pm.goToSleep(SystemClock.uptimeMillis());
		android.util.Log.i("cxq", "screenOff");

	}
}
 

3、自定义广播,用于控制屏幕的唤醒和熄灭,这样做的好处是可以在其他APP中也实现屏幕的控制

package testWakeAndLock;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class ScreenControlBroadcast extends BroadcastReceiver {

	private String op = "on";

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		android.util.Log.i("cxq", "ScreenControlBroadcast");
		op = intent.getStringExtra("screen");
		WakeAndLock wakeAndLock = new WakeAndLock();
		if (op.equals("off")) {
			wakeAndLock.screenOff();
		} else {
			wakeAndLock.screenOn();
		}
	}

}

4、在Manifest文件中注册广播

 <receiver android:name="testWakeAndLock.ScreenControlBroadcast" >
            <intent-filter>
                <action android:name="testWakeAndLock.ScreenControlBroadcast" />
            </intent-filter>
  </receiver>

5、怎么在其他APP中调用?

其实有很多中方式,但是本文介绍一种方便快捷的方法,直接通过adb命令调用 格式如下:

亮屏

am broadcast -a testWakeAndLock.ScreenControlBroadcast --es screen on

灭屏

am broadcast -a testWakeAndLock.ScreenControlBroadcast --es screen off