遵循本指南https://developer.android.com/training/monitoring-device-state/battery-monitoring.html
我制作了一个接收器,每次插入或拔出充电器时都应将电池信息记录到文件中。活动读取此文件的内容并将其显示在屏幕上。无论应用程序运行如何,这应该始终有效,但事实并非如此。它仅在应用程序打开/内存时进行注册,当我清除内存或重新启动时,它会停止工作。
清单:
<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();
}
}
}
这是应用程序打开后拔下插头后的样子:
当它不是时,它就是空的。
答案 0 :(得分:1)
尝试将android:enabled="true"
设置为您的接收器
喜欢这个
<receiver android:name=".Receiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
我只是在我的应用程序中实现它的方式,它的工作原理。但我用right click->new->other->broadcast receiver
插入intent-filter后,我得到了这样的代码
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
它实际上调用onReceive
方法
答案 1 :(得分:0)
你尝试过使用唤醒锁吗?一般来说,应用程序会在接收到广播时不会唤醒它(在少数设备中发生),然后尝试使用唤醒锁定来强制唤醒设备。
如何使用唤醒锁:
//注册唤醒锁
if (mWakeLock == null) {
PowerManager pm = (PowerManager)yourcontext.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, yourcontext);
mWakeLock.setReferenceCounted(false);
}
//使用acquire
应用唤醒锁定
mWakeLock.acquire();