下面给出的代码用于跟踪设备的电池电量并将其存储在数据库中。为了获取电池电量,每 3 分钟调用一次函数“batterylevel”,并将电池电量插入到 db 表中。当设备充满电时,代码还可以在另一个数据库表中节省时间。一段时间内一切正常。但是大约30分钟后出现问题,正在运行的服务自动进入其oncreate方法,之后该服务不会显示任何日志,最终服务停止导致强制关闭,同时尝试手动停止服务。
public class BatteryLevelService extends Service {
BroadcastReceiver batteryLevelReceiver;
Timer t ;
Calendar cal;
Date lastBatteryFullTime;
Context context;
int sec;
int lastFullChargeYear,lastFullChargeMonth,lastFullChargeDay;
int lastFullChargeHour,lastFullChargeMinute,lastFullChargeSecond;
private File dir;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate(){
Log.d("Service", "oncreate Service Started");
}
private void batteryLevel() {
cal=Calendar.getInstance();
long currentHour=cal.get(Calendar.HOUR_OF_DAY);
long currentMinute=cal.get(Calendar.MINUTE);
long currentSecond=cal.get(Calendar.SECOND);
final String currentTime=currentHour+" : "+currentMinute+" : "+currentSecond;
Intent batteryIntent = registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int rawlevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
MainActivity.sqladp.insertBatteryLevel(level, currentTime);
if(level==100){
cal=cal.getInstance();
lastFullChargeYear=cal.get(Calendar.YEAR);
lastFullChargeMonth=cal.get(Calendar.MONTH);
lastFullChargeDay=cal.get(Calendar.DAY_OF_MONTH);
lastFullChargeHour=cal.get(Calendar.HOUR_OF_DAY);
lastFullChargeMinute=cal.get(Calendar.MINUTE);
lastFullChargeSecond=cal.get(Calendar.SECOND);
lastBatteryFullTime=new Date(lastFullChargeYear, lastFullChargeMonth, lastFullChargeDay, lastFullChargeHour, lastFullChargeMinute);
String[] lastFullChargeTime=lastBatteryFullTime.toString().split("GMT");
MainActivity.sqladp.deleteLastFullBattery();
MainActivity.sqladp.insertLastUsage("Battery", "", lastFullChargeTime[0], "");
}
Log.d("Battery level", ""+level + "%");
}
@Override
public void onStart(Intent intent, int startId) {
Log.d("Service", "Service Started");
t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
batteryLevel();
Log.d("", "batlevel ");
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
3*60*1000);
}
@Override
public void onDestroy() {
Log.d("service", "onDestroy");
t.cancel();
}