Skip to content Skip to sidebar Skip to footer

Getting Battery Status Even When The Application Is Closed

Hey I am trying to make an application that tells me when the battery is full when the phone is connected to power. I made a service and used a broadcast receiver in that to check

Solution 1:

System messages like the battery level are sent as a Broadcast through the whole system. You can receive them with a so called BroadcastReceiver.

While Activities have an UI, you need to use a Service which are meant to be used for longer work in the background while your App is not visible. Your App has to be started at least once before for you to be able to start this Service.

MainActivity.java

publicclassMainActivityextendsActionBarActivity {

    private MyService service;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

MyService.java

publicclassMyServiceextendsService {

    @OverridepublicintonStartCommand(Intent intent, int flags, int startId) {
        Log.d("MyService", "onStartCommand");
        // do not receive all available system information (it is a filter!)finalIntentFilterbattChangeFilter=newIntentFilter(
                Intent.ACTION_BATTERY_CHANGED);
        // register our receiverthis.registerReceiver(this.batteryChangeReceiver, battChangeFilter);
        returnsuper.onStartCommand(intent, flags, startId);
    }

    privatefinalBroadcastReceiverbatteryChangeReceiver=newBroadcastReceiver() {

        @OverridepublicvoidonReceive(final Context context, final Intent intent) {
            checkBatteryLevel(intent);
        }
    };

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

    privatevoidcheckBatteryLevel(Intent batteryChangeIntent) {
        // some calculationsfinalintcurrLevel= batteryChangeIntent.getIntExtra(
                BatteryManager.EXTRA_LEVEL, -1);
        finalintmaxLevel= batteryChangeIntent.getIntExtra(
                BatteryManager.EXTRA_SCALE, -1);
        finalintpercentage= (int) Math.round((currLevel * 100.0) / maxLevel);

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

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

}

Manifest.xml: You need an entry for your Serivice - just like for an Activity.

<?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.example.mybatteryservice"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="19" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name="com.example.mybatteryservice.MainActivity"android:label="@string/app_name" ><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activityandroid:name="com.example.mybatteryservice.SecondActivity" ></activity><serviceandroid:name="com.example.mybatteryservice.MyService" ></service></application></manifest>

Please let me know if you have any more questions!

Best regards Vincent

Solution 2:

Write your code as a service. Its simple to use

publicclassClassNameextendsService{

         //write your code


       }

also add it on manifest

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

/////////////////// New Codes ///////////////////

publicclassBatCheckextendsService {
  publicvoidonCreate() {
    super.onCreate();


            BroadcastReceiverbr=newBroadcastReceiver() {
        @OverridepublicvoidonReceive(Context context, Intent intent) {

        intstatus= intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                  booleanisCharged= status == BatteryManager.BATTERY_STATUS_FULL;

                      if(isCharged){

                         // write your code

                          }
        }
    };

}

}

//////////////// Another One ///////////////////

In your manifest

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

In your activity

publicclassBatCheckextendsBroadcastReceiver {
    @OverridepublicvoidonReceive(Context context, Intent intent) { 
        intstatus= intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        booleanisCharged= status == BatteryManager.BATTERY_STATUS_FULL;

              if(isCharged){

                 // write your code

                  }

    }
}

Post a Comment for "Getting Battery Status Even When The Application Is Closed"