即使应用程序关闭也能获得电池状态

时间:2014-05-20 11:11:58

标签: android android-service android-notifications android-alarms

嘿我正在尝试制作一个应用程序,告诉我手机连接电源时电池已满。 我做了一项服务并使用了广播接收器来检查电池状态。 每当我连接电源或断开电源时,我的应用程序都会崩溃。该服务仍在运行,我会在电池充满时收到通知。

我不知道为什么应用程序会一次又一次地崩溃。 这是我的代码

公共类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();

}

}

请帮帮我。

感谢。

2 个答案:

答案 0 :(得分:2)

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

虽然活动拥有用户界面,但您需要使用 服务 。它们用于在您的应用程序不可见时在后台执行更长时间的工作。您的应用必须至少启动一次才能从活动中启动此服务。 一些额外的信息: 还有 AsyncTasks 。当您的应用程序可见且正常工作时(例如将数据从Internet加载到 ListView 或其他内容),这些内容将用于填充内容。您必须执行任务,因为如果您不这样做,您的UI将会冻结。您在不使用任务的情况下编写的几乎所有内容都将在UI线程中执行。如果UI线程变忙,用户将无法执行任何操作。

现在这里有一些代码:

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 something about
        // that. This one is an Unbounded Service.
        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:您需要一个Serivice条目 - 就像活动一样。

<?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>

如果您有任何其他问题,请与我们联系!

祝你好运 文森特

答案 1 :(得分:1)

将您的代码编写为服务。它易于使用

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

                  }

    }
}
相关问题