按照本指南https://developer.android.com/training/monitoring-device-state/battery-monitoring.html
我制作了一个接收器,每次插入或拔出充电器时都应将电池信息记录到文件中。Activity 读取该文件的内容并将其显示在屏幕上。无论应用程序运行如何,这都应该始终有效,但事实并非如此。它仅在应用程序打开/在内存中时注册,当我清除内存或重新启动时它停止工作。
显现:
<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();
}
}
}
这是应用打开时拔下电源后的样子:
当它不是时,它只是空的。