【发布时间】:2014-05-20 11:11:57
【问题描述】:
嘿,我正在尝试制作一个应用程序,当手机连接到电源时,它会告诉我电池何时充满。 我做了一项服务,并在其中使用了广播接收器来检查电池状态。 每当我连接或断开手机电源时,我的应用程序都会崩溃。该服务仍在运行,当电池充满时我会收到通知。
我不知道为什么应用程序一次又一次地崩溃。 这是我的代码
公共类 Srvc 扩展服务{
@Override
public int onStartCommand(Intent intent, int flags, int startId){
// TODO Auto-generated method stub
final IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
this.registerReceiver(this.br, ifilter);
System.out.println("started the service");
return super.onStartCommand(intent,flags,startId);
}
public final BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("inside on recieve");
chckbttry(intent);
}
};
private void chckbttry(Intent intent) {
// TODO Auto-generated method stub
System.out.println("inside chckbttry method");
final int currLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
final int maxLevel = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharged = status == BatteryManager.BATTERY_STATUS_FULL;
final int percentage = (int) Math.round((currLevel * 100.0) / maxLevel);
if (status == BatteryManager.BATTERY_STATUS_CHARGING)
{
System.out.println("calling the BrdCst_strt");
if (percentage == 100 || isCharged==true) {
System.out.println("bttry fully chrged");
Intent i = new Intent(getBaseContext(),PlayMus.class); //call another activity
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("msg", "Battery fully charged");
getApplication().startActivity(i);
}
else
{
System.out.println("not yet charged");
Intent i = new Intent(getBaseContext(), Test.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("msg", "Battery not fully charged");
getApplication().startActivity(i);
}
}
if (status == BatteryManager.BATTERY_STATUS_DISCHARGING)
{
System.out.println("unregistering the service");
unregisterReceiver(br);
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("service stopped");
unregisterReceiver(br);
super.onDestroy();
}
}
请帮帮我。
谢谢。
【问题讨论】:
-
您需要为此使用服务。你了解服务吗?
-
没有。正如我所说,我是新手。我找到了很多关于获取服务和使用服务的答案,但我不明白。你能给我解释一下吗?这将是真正的heplfull。
标签: android android-service android-notifications android-alarms