这是我的代码:
public class PowerConnectionReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
intent = new Intent (context, MainActivity.class);
intent.putExtra("Charging", isCharging);
startActivity(intent);
}
}
我认为它应该可以正常工作,但我在startActivity()
收到错误。它看起来像是未定的。有人知道这有什么问题吗?
答案 0 :(得分:4)
BroadcastReceiver
未展开Context
,因此它没有方法startActivity
。您应该使用传递给onReceive
的上下文:
context.startActivity(intent);