Monday, July 29, 2013

Week 12: Android Battery Data

At the beginning of this week, I continued working on the Android development training. I learned about switching between Activities by using Intents, the lifecycle of an Activity, navigating between different XML pages, and dynamically generating UI elements. I began working on collecting sources of entropy with Adam. We plan on eventually combining the data collection code into a unified app, but for right now, I am working on getting battery specifications and status as well as process statistics from the OS such as how many processes are currently running, how much memory each process is using, the network bandwidth of each process, and other system information.

I started out researching a way to get battery information from the Android environment. The android.os API provides the BatteryManager class, which contains several string constants such as EXTRA_TEMPERATURE, EXTRA_VOLTAGE, EXTRA_LEVEL, and EXTRA_STATUS. When I tried to display those constants in TextViews directly, however, they all came up as either 0s or nulls. I did a little more research and discovered that these constants can only be accessed through a BroadcastReceiver. The receiver is registered using this function call:

this.registerReceiver(this.mBatInfoReceiver,
                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));


This registers mBatInfoReceiver, which is declared as follows:

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent intent) {
          temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
          volt = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
          tech = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);
          stat = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
          level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
          scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
        }
      };


So that each of the variables assigned in onReceive() is updated whenever the Android system triggers the ACTION_BATTERY_CHANGED intent. All I needed to do once these variables were updated was format some of them (temperature is given in tenths of a degree Celcius and voltage is given in millivolts). This code worked quite nicely, giving me all of the battery information that can be updated in real time by the press of a button. The next step for this unified app will be for me to start working on system process data collection.

No comments:

Post a Comment