此代码应该建议手机是否正在实时充电,更改文本视图。
public class MainActivity extends AppCompatActivity {
TextView testoStatoCarica;
String positivo = "Sto caricando";
String negativo = "Non in carica";
boolean variabileStato;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testoStatoCarica = (TextView) findViewById(R.id.TestoStatoCarica);
//Ricevo lo stato di carica
registerReceiver( null ,new IntentFilter("broadcastStato"));
BroadcastReceiver ricettore = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle b1 = intent.getExtras();
variabileStato = intent.getBooleanExtra("isCharging", isCharging);
}
};
}
}
在另一个类(PowerConnectionReceiver)中我做了这个!
public class PowerConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
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);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
Bundle bundle = intent.getExtras();
Intent i1 = new Intent("broadcastStato");
i1.putExtra("isCharging", isCharging);
Intent i2 = new Intent("broadcastTipo1");
i2.putExtra("usbCharge", usbCharge);
Intent i3 = new Intent("broadcastTipo2");
i3.putExtra("acCharge", acCharge);
context.sendBroadcast(i1);
context.sendBroadcast(i2);
context.sendBroadcast(i3);
}
}
现在,问题在于我真的不明白在我的MainActivity中做了什么,并且在最后一堂课中创造了booleand!有人可以帮忙吗?
答案 0 :(得分:0)
查看Monitoring the Battery Level and Charging State文章,其中包含代码示例:
首先,您需要在BroadcastReceiver
中指定AndroidManifest
:
<receiver android:name=".PowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
然后,指定PowerConnectionReceiver
:
public class PowerConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
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);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
}
}
现在,将新值从PowerConnectionReceiver
传递到MainActivity
的最后一步:
您可以在此处找到该教程:https://trinitytuts.com/pass-data-from-broadcast-receiver-to-activity-without-reopening-activity/
(一旦您传递了新值 - 您可以更新TextView
的文字)
就是这样!我希望,这有帮助