这是我在点击UI上的按钮时执行的功能&它在TextView上显示字符串str(充电状态)。
public void checkStatus (View view) {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Context context = this;
Intent batteryStatus = context.registerReceiver(null, ifilter);
// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
int perc = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
String str;
if (perc == 100) {
str = "Fully charged";
} else if (isCharging) {
str = "Charging";
} else {
str = "Not Charging";
}
TextView textview = (TextView) findViewById(R.id.textView);
textview.setText(str);
}
现在我要做的是定期检查电池和电池。一旦它是100%(完全充电)然后调用一个函数,让我们称之为DiscntCharger()
根据我的研究,我需要在这里使用IntentService来监控充电状态&一旦发现电池充满电,就需要在我的主要活动中调用该功能。但是,由于我对Android开发还很新,我无法理解如何实现它。
如果有人能指出我正确的方向,我真的很感激。
答案 0 :(得分:1)
试试这个。 在您的活动类中创建广播接收器并在电池充满时执行任何操作
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
textview.setText(String.valueOf(level) + "%");
// do your stuff here
}
};
并在onCreate()中注册广播类
registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
答案 1 :(得分:0)
答案 2 :(得分:0)
你需要写一个public static String URL = "jdbc:mysql://localhost/javaDb?allowMultiQueries=true";
来实现你想要的。
在BroadcastReceiver
AndroidManifest.xml
撰写<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>
BroadcastReceiver
在此处详细了解:Monitoring Device Battery Status
注意事项:
使用Android O,您可能需要转到public class PowerConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isFull = status == BatteryManager.BATTERY_STATUS_FULL;
// Do your job after checking for isFull
}
}
或JobScheduler
,因此请在此处阅读Background Services in Android O
答案 3 :(得分:0)