package com.example.battery;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.widget.TextView;

public class BatteryStatusActivity extends Activity {
    private TextView batteryLevel;
    private TextView batteryState;

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

        batteryLevel = (TextView) findViewById(R.id.batteryLevel);
        batteryState = (TextView) findViewById(R.id.batteryState);

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        filter.addAction(Intent.ACTION_BATTERY_LOW);
        filter.addAction(Intent.ACTION_BATTERY_OKAY);

        BroadcastReceiver batteryReceiver = new BatteryReceiver();
        registerReceiver(batteryReceiver, filter);
    }

    public class BatteryReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(
                    Intent.ACTION_BATTERY_CHANGED)) {
                int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
                batteryLevel.setText(level + "/" + scale);
            }
            if (intent.getAction().equals(
                    Intent.ACTION_BATTERY_LOW)) {
                batteryState.setText(context.getText(R.string.batteryLow));
            }
            else if (intent.getAction().equals(
                    Intent.ACTION_BATTERY_OKAY)) {
                batteryState.setText(context.getText(R.string.batteryOK));
            }
        }
    }
}
