Pra*_*nna 6 android broadcastreceiver android-intent batterylevel
我已经看过registerReceiver必须调用它的帖子(在清单中没有定义)以接收ACTION_BATTERY_LOW意图.
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
//....
registerReceiver(new BatteryLevelReceiver(), new IntentFilter(
Intent.ACTION_BATTERY_LOW));
}
// .......
}
Run Code Online (Sandbox Code Playgroud)
广播接收器
public class BatteryLevelReceiver extends BroadcastReceiver
{
private static final String TAG = BatteryLevelReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "onReceive");
}
}
Run Code Online (Sandbox Code Playgroud)
我没有在logcat中看到"onReceive"日志语句.我正在使用模拟器来模拟电池低电量状态,使用telnet 5554和执行power capacity 10.我确实看到模拟器中的电池状态发生了变化但没有触发意图.
此外,如果我必须registerReceiver()在一个活动内部打电话而我没有打电话unregisterReceiver,onStop或者onDestroy它可以吗?如果不行,即使我的应用程序不在前台,我将如何注册接收器以接收系统意图?(除了使用清单).
您可以在清单中添加以下代码。
<receiver android:name=".yourpackage.BroadCastNotifier" >
<intent-filter>
<action android:name="android.intent.action.BATTERY_LOW" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
在你的BroadCastNotifier Class
package yourpackage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BroadCastNotifier extends BroadcastReceiver {
private final static String TAG = "BroadCastNotifier";
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if(Intent.ACTION_BATTERY_LOW.equalsIgnoreCase(intentAction)){
Log.e(TAG, "GOT LOW BATTERY WARNING");
}
}
}
Run Code Online (Sandbox Code Playgroud)
您将收到日志消息GOT LOW BATTERY WARNING当电池电量不足时,
虽然上面的代码可能工作的最佳方法是不使用广播来执行此类操作,但您可以按照此处所述监视电池电量。您可以使用下面的代码来确定您的电池,这更容易。
int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level / (float)scale;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3089 次 |
| 最近记录: |