我想以5秒的间隔获得电池电流和电压。
但在我的来源中,电压和电流以随机间隔变化。
如5秒,10秒,9秒,.......
我听说BroadcastReceiver需要在10秒内返回值。
我想这是一个原因,但我不知道如何解决这个问题。
package com.example.hubertlee.batterywearrate;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView batteryInfo;
Long avgCurrent = null, currentNow = null;
int count = 0;
float power = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BatteryManager mBatteryManager = (BatteryManager) getSystemService(Context.BATTERY_SERVICE);
batteryInfo = (TextView) findViewById(R.id.textViewBatteryInfo);
this.registerReceiver(this.batteryinfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
avgCurrent = mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE);
currentNow = mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
}
}
private BroadcastReceiver batteryinfoReceiver = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent){
int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0);
int icon_small = intent.getIntExtra(BatteryManager.EXTRA_ICON_SMALL,0);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
boolean present = intent.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
String technology = intent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
float temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
float voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
batteryInfo.setText("Health: " + health + "\n" + "Icon small : "+icon_small+"\n" +
"Level : "+level+"\n"+"Present : "+present+"\n"+"Scale: "+
scale+"\n"+"Status :"+status+"\n"+ "Technology:"+technology+"\n"+
"Temperature :"+temp/10+"'C\n"+"Voltage:"+voltage/1000+"V\n"+"BATTERY_PROPERTY_CURRENT_AVERAGE = "
+ avgCurrent + "mAh"+"\n"+"BATTERY_PROPERTY_CURRENT_NOW = " + currentNow + "mAh"+"\n"+"count ="+count);
count++;
}
};
}
答案 0 :(得分:0)
如果您希望以修复间隔运行代码,请查看警报管理器: https://developer.android.com/reference/android/app/AlarmManager.html
就像塞尔文所说,广播只有在改变时才会被呼叫。