电池信息变化统计与展示

此文章仅作为学习交流所用

      转载或引用请务必注明原文地址:http://blog.csdn.net/ningchao328/article/details/51513898

      谢谢!  

--------------------------------------------------------------------------------------------------------------------


功能要求:

1>.要求检测到安卓手机的电量,电压,连接状态,充电连接方式,以及当前的时间,而这些与电池相关的信息都会通过系统广播发出来,去注册相应广播接收即可,然后通过BatteryManager这个类来获取这些信息。

2.>首先通过TextView控件做展示;其次将这些信息保存到data/data/包名/files下,文件名为data;最后还得将这些数据通过listview控件展示(因为是要求电量发生变化就记录保存一次相应信息;相应每改变一次,listview里面就相应的增加一次改变的信息)

3>代码中写的虽然是通过定时器每隔30秒就去获取一下系统的电池变化,然后将每次变化信息保存到data/data/包名/files下,然后再将每次电池变化信息依次展示到listview里面。


1.主要代码

package com.zhc.battery;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;

import android.R.string;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
    private TextView textViewLevel = null;
    private TextView textViewLevel1 = null;
    private TextView textViewLevel2 = null;
    private TextView textViewLevel3 = null;
    private TextView textViewLevel4 = null;
    private ListView textViewLevel5 = null;

    private int batteryLevel;

    private int batteryScale;

    private Button buttonBatteryShow;

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            // 获取当前电量,如未获取具体数值,则默认为0
            batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);

            // 获取最大电量,如未获取到具体数值,则默认为100
            batteryScale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);

            // 显示电量
            textViewLevel.setText("电量" + (batteryLevel * 100 / batteryScale)
                    + "%");

            /**
             * 时间
             */
            SimpleDateFormat sDateFormat = new SimpleDateFormat(
                    "yyyy-MM-dd hh:mm:ss:SSS ");
            String date = sDateFormat.format(new java.util.Date());
            textViewLevel1.setText("battery: date=" + date);

            /**
             * 电池状态
             */
            int status = intent.getIntExtra("status", 0);
            String statusString = "";
            switch (status) {
            case BatteryManager.BATTERY_STATUS_UNKNOWN:
                statusString = "unknown";
                break;
            case BatteryManager.BATTERY_STATUS_CHARGING:
                statusString = "charging";
                break;
            case BatteryManager.BATTERY_STATUS_DISCHARGING:
                statusString = "discharging";
                break;
            case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                statusString = "not charging";
                break;
            case BatteryManager.BATTERY_STATUS_FULL:
                statusString = "full";
                break;
            }
            textViewLevel2.setText("status " + statusString);

            /**
             * 电压
             */
            int voltage = intent.getIntExtra("voltage", 0);
            textViewLevel3.setText("voltage=" + voltage);

            /**
             * Usb还是ac供电
             */
            int plugged = intent.getIntExtra("plugged", 0);
            String acString = "";
            switch (plugged) {
            case BatteryManager.BATTERY_PLUGGED_AC:
                acString = "plugged ac";
                break;
            case BatteryManager.BATTERY_PLUGGED_USB:
                acString = "plugged usb";
                break;
            }
            textViewLevel4.setText("acString=" + acString);

            String inputText = "\r\n" + "电量="
                    + (batteryLevel * 100 / batteryScale) + "%" + "   "
                    + "battery:date(时间)=" + date + "   " + "status(电池状态) "
                    + statusString + "    " + "voltage(电压)=" + voltage + "   "
                    + "acString(供电情形)=" + acString + "\r\n";

            /*
             * if (batteryScale<batteryScale) { save(inputText); batteryScale--;
             * };
             */

            save(inputText);
            String inputText1 = load();
            if (!TextUtils.isEmpty(inputText1)) {
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                        MainActivity.this, android.R.layout.simple_list_item_1
                        );
                adapter.add(inputText1);
                textViewLevel5.setAdapter(adapter);
            }
            ;
        }
    };

    public void save(String inputText) {
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            out = openFileOutput("data", Context.MODE_APPEND);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public String load() {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = openFileInput("data");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();

    };

    private Handler handler = new Handler();

    private Runnable task = new Runnable() {
        public void run() {
            // TODOAuto-generated method stub
            handler.postDelayed(this, 30* 1000);// 设置延迟时间,此处是5秒
            // 需要执行的代码
            buttonBatteryShow.performClick();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FileOutputStream out = null;
        try {
            out = openFileOutput("data", Context.MODE_APPEND);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        textViewLevel = (TextView) findViewById(R.id.textViewBattery);
        textViewLevel1 = (TextView) findViewById(R.id.textViewBattery1);
        textViewLevel2 = (TextView) findViewById(R.id.textViewBattery2);
        textViewLevel3 = (TextView) findViewById(R.id.textViewBattery3);
        textViewLevel4 = (TextView) findViewById(R.id.textViewBattery4);
        textViewLevel5 = (ListView) findViewById(R.id.textViewBattery5);
        buttonBatteryShow = (Button) findViewById(R.id.button_show_battery);
        buttonBatteryShow.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                IntentFilter intentFilter = new IntentFilter(
                        Intent.ACTION_BATTERY_CHANGED);

                // 注册接收器以获取电量信息
                registerReceiver(broadcastReceiver, intentFilter);
            }
        });

        /*
         * IntentFilter intentFilter = new IntentFilter(
         * Intent.ACTION_BATTERY_CHANGED);
         *
         * // 注册接收器以获取电量信息 registerReceiver(broadcastReceiver, intentFilter);
         */

        handler.postDelayed(task, 30* 1000);// 延迟调用
        //handler.post(task);// 立即调用
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}




2.布局代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textViewBattery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0" />

    <TextView
        android:layout_marginTop="10dp"
        android:id="@+id/textViewBattery1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textViewBattery"
        android:text="1" />

    <TextView
        android:layout_marginTop="10dp"
        android:id="@+id/textViewBattery2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textViewBattery1"
        android:text="2" />

    <TextView
        android:layout_marginTop="10dp"
        android:id="@+id/textViewBattery3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textViewBattery2"
        android:text="3" />

    <TextView
        android:layout_marginTop="10dp"
        android:id="@+id/textViewBattery4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textViewBattery3"
        android:text="4" />
    <ListView
      android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         android:id="@+id/textViewBattery5"
         android:layout_below="@id/textViewBattery4"
         android:transcriptMode="alwaysScroll" ></ListView>

    <Button
        android:id="@+id/button_show_battery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="showBattery" >
    </Button>

</RelativeLayout>

3.效果图

1>

2>



改进版:http://blog.csdn.net/ningchao328/article/details/51925651




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值