【问题标题】:Getting battery status even when the application is closed即使应用程序关闭也能获取电池状态
【发布时间】: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


【解决方案1】:

电池电量等系统消息作为广播通过整个系统发送。您可以使用所谓的 BroadcastReceiver 接收它们。

虽然 Activity 有一个 UI,但您需要使用 Service,该服务旨在用于在后台进行更长时间的工作,而您的应用程序不可见。您的应用必须至少启动一次才能启动此服务

MainActivity.java

public class MainActivity extends ActionBarActivity {

    private MyService service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (service == null) {
            // start service
            Intent i = new Intent(this, MyService.class);
            startService(i);
        }
        // finish our activity. It will be started when our battery is full.
        finish();
    }
}

MyService.java

public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("MyService", "onStartCommand");
        // do not receive all available system information (it is a filter!)
        final IntentFilter battChangeFilter = new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED);
        // register our receiver
        this.registerReceiver(this.batteryChangeReceiver, battChangeFilter);
        return super.onStartCommand(intent, flags, startId);
    }

    private final BroadcastReceiver batteryChangeReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(final Context context, final Intent intent) {
            checkBatteryLevel(intent);
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        // There are Bound an Unbound Services - you should read about the differences. This one is an unbound one.
        return null;
    }

    private void checkBatteryLevel(Intent batteryChangeIntent) {
        // some calculations
        final int currLevel = batteryChangeIntent.getIntExtra(
                BatteryManager.EXTRA_LEVEL, -1);
        final int maxLevel = batteryChangeIntent.getIntExtra(
                BatteryManager.EXTRA_SCALE, -1);
        final int percentage = (int) Math.round((currLevel * 100.0) / maxLevel);

        Log.d("MySerive", "current battery level: " + percentage);

        // full battery
        if (percentage == 100) {
            Log.d("MySerive", "battery fully loaded");
            Intent intent = new Intent(getBaseContext(), SecondActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getApplication().startActivity(intent);
        }
        // do not forget to unregister
        unregisterReceiver(batteryChangeReceiver);
    }

}

Manifest.xml:您的服务需要一个条目 - 就像 Activity 一样。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mybatteryservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mybatteryservice.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.example.mybatteryservice.SecondActivity" >
        </activity>
        <service android:name="com.example.mybatteryservice.MyService" >
        </service>
    </application>

</manifest>

如果您还有任何问题,请告诉我!

最好的问候 文森特

【讨论】:

  • 我使用了您的代码并添加了另一件事,即我还检查了电池状态是否正在充电。每当我将手机连接到充电器或断开连接时,我的应用程序就会崩溃。我不知道为什么,请你帮忙?
  • 对不起,我的回答迟了。最近几天我没有检查堆栈溢出。你还需要帮助吗?给我看看你的原木猫吧。
【解决方案2】:

将您的代码编写为服务。使用简单

public class ClassName extends Service{

         //write your code


       }

也将其添加到清单中

<service android:name="com.test.ClassName">               
           </service>

/////////////////////////////////////////////////////////////////////////////////////

public class BatCheck extends Service {
  public void onCreate() {
    super.onCreate();


            BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                  boolean isCharged = status == BatteryManager.BATTERY_STATUS_FULL;

                      if(isCharged){

                         // write your code

                          }
        }
    };

}

}

//////////////////////////////////////////////////////////////////////////////

在您的清单中

   <receiver android:name=".BatCheck">
  <intent-filter>
    <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
    <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
  </intent-filter>
</receiver>

在你的活动中

    public class BatCheck extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) { 
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharged = status == BatteryManager.BATTERY_STATUS_FULL;

              if(isCharged){

                 // write your code

                  }

    }
}

【讨论】:

  • 我在课堂上具体做什么?正如我所说,我是新手,我知道的不多。
  • 你必须为电池意图实现一个意图接收器。只需查看 android 开发者网站即可。
  • 非常感谢...这些真的很有帮助..!!!我需要在清单中添加权限吗?
  • 请多告诉我一点。如果我创建一个扩展广播接收器的 BatChckBR 类,然后从我的服务中调用这个类,它的工作方式是否相同?我可以只使用 ACTION_POWER_CONNECTED,因为只要连接了电源,我只需要检查吗?
  • 如果您有像我的代码这样的广播接收器,则无需服务。它在电池电量发生变化时起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多