遇到难题求高手帮忙解决--Android P开始监听不到关机广播
背景:最近在做一个关于android的续航时间测试apk,从开始测试记录时间到低电自动关机时这整个的时间,当前采用监听关机广播的来实际统计续航时间,但遇到的问题是同样的测试apk在android8及以下系统均能正常监听到关机广播,但从android 9开始就监听不到关机广播了。
下面是我的监听广播注册方法(采用静态注册关机 广播方式)
AndroidManifest.xml如下
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.dou.dou">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver
android:name="com.dou.dou.ShutDownBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<!--<category android:name="android.intent.category.HOME" />-->
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
<!--<category android:name="android.intent.category.HOME" />-->
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
</manifest>
下面是实现接收关机广播的处理实现
package com.dou.dou;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ShutDownBroadcastReceiver extends BroadcastReceiver {
// private static final String TAG = "ShutdownBroadcastReceiver";
private static final String ACTION_SHUTDOWN = "android.intent.action.ACTION_SHUTDOWN";
@Override
public void onReceive(Context context, Intent intent){
System.out.println("---------Shut down-------------");
File file = new File ("/sdcard/result.txt");
if(intent.getAction().equals(ACTION_SHUTDOWN)){
try {
if(!file.exists())
{
file.createNewFile();
}
FileWriter writer = null;
writer = new FileWriter(file, true);
writer.write("Shut_down [" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()) + "]\n");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Intent intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
intent.putExtra("android.intent.extra.KEY_CONFIRM", false);
试试这个 intent 徐颖科 发表于 2020-6-11 08:02
试试这个 intent
刚试过,也是不行。
页:
[1]