android studio简单实现监听系统息屏亮屏的广播
时间: 2023-12-09 14:36:45 浏览: 203
android广播简单使用
以下是Android Studio简单实现监听系统息屏亮屏的广播的步骤:
1.在AndroidManifest.xml文件中添加权限和广播接收器的声明:
```xml
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<receiver android:name=".ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.SCREEN_OFF" />
</intent-filter>
</receiver>
```
2.创建一个ScreenReceiver类,继承BroadcastReceiver类,并实现onReceive()方法:
```java
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// 屏幕亮起时的操作
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// 屏幕熄灭时的操作
}
}
}
```
3.在onReceive()方法中添加相应的操作,例如:
```java
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Toast.makeText(context, "屏幕已亮起", Toast.LENGTH_SHORT).show();
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Toast.makeText(context, "屏幕已熄灭", Toast.LENGTH_SHORT).show();
}
}
}
```
4.在需要监听屏幕亮灭的Activity中注册广播接收器:
```java
public class MainActivity extends AppCompatActivity {
private ScreenReceiver mScreenReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScreenReceiver = new ScreenReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mScreenReceiver);
}
}
```
5.在Activity销毁时注销广播接收器。
阅读全文