根据此指南,我创建了一个接收器,应该在每次插入或拔出充电器时记录电池信息到文件中。该活动读取此文件的内容并将其显示在屏幕上。这应该始终工作,无论运行哪个应用程序,但实际情况并非如此。只有当应用程序处于打开/内存状态时,它才能注册,当我清除内存或重新启动后,它就停止工作了。
清单:
<receiver android:name=".Receiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
接收器:
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent chargingIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
final int status = chargingIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
int level = chargingIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int plugged = chargingIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
Battery battery = new Battery();
battery.setLevel(level);
battery.setDate(new Date());
battery.setPlugged(plugged);
battery.setStatus(status);
Logger.log(JSON.toJSONString(battery));
}
}
日志记录器
public class Logger {
public static void log(String text)
{
File logFile = new File(Environment.getExternalStorageDirectory().getPath()+"/batterylog.txt");
Log.d("files"," logfile "+logFile+": "+logFile.exists());
if (!logFile.exists())
{
try
{
logFile.createNewFile();
Log.d("files","new logfile created"+logFile);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text).append("\r\n");
buf.flush();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是在应用程序打开的情况下拔掉电源后的样子:
![enter image description here](https://istack.dev59.com/JfgNp.webp)
BroadcastReceiver
应该能够在应用程序关闭的情况下触发。但事实并非如此? - Asalas77