Android电池检测(2)

改进版就直接贴代码了

1.MainActivity里面代码

<pre name="code" class="html">package com.zhc.battery;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.BatteryManager;
import android.os.Bundle;
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.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
	private TextView textViewLevel = null;
	private ListView ListViewBattery5 = null;
	private int oldbatteryLevel = 0;
	private int batteryLevel;
	private int BatteryT;
	private String BatteryTc;
	private int BatteryTcc;
	private String nul = "   ";
	private int batteryScale;
	private Button buttonBatteryShow;//初始化按钮

	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 电池温度
			BatteryT = intent.getIntExtra("temperature", 0);
			// BatteryTc=(BatteryT+"").substring(0,3);//对温度的数据长度做截取,但在模拟器上报错,手机上可以正常运行。
			BatteryTc = BatteryT + "";
			BatteryTcc = Integer.parseInt(BatteryTc);

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

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

			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy年MM月dd日 HH:mm:ss ");
			Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
			String date = formatter.format(curDate);

			/**
			 * 电池状态
			 */
			int status = intent.getIntExtra("status", 0);
			String statusString = "";
			switch (status) {
			case BatteryManager.BATTERY_STATUS_UNKNOWN:
				statusString = "未知状态";
				break;
			case BatteryManager.BATTERY_STATUS_CHARGING:
				statusString = "充电状态";
				break;
			case BatteryManager.BATTERY_STATUS_DISCHARGING:
				statusString = "放电状态";
				break;
			case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
				statusString = "未充电   ";
				break;
			case BatteryManager.BATTERY_STATUS_FULL:
				statusString = "充满状态";
				break;
			}


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

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

			String inputText = "\r\n" + "时间:" + date + nul + statusString + nul
					+ "电量:" + (batteryLevel * 100 / batteryScale) + "%" + nul
					+ "电压:" + voltage + "mV" + nul + "温度:" + (BatteryTcc * 0.1)
					+ "℃" + nul + "供电:" + acString + "\r\n";

			textViewLevel.setText(inputText);//数据展示到TextView

			if (batteryLevel != oldbatteryLevel) {//添加电量变化的限制条件
				oldbatteryLevel = batteryLevel;
				// 保存数据
				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);
					ListViewBattery5.setAdapter(adapter);
				}
			}
			;

		}

		/**
		 * 保存数据到文件
		 * 
		 * @param inputText
		 */
		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();
				}
			}
		}

		/**
		 * 从文件里面读取数据
		 * 
		 * @return
		 */
		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) {
					line = line + "\n";
					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() {
	// handler.postDelayed(this, 30 * 1000);// 设置延迟时间,此处是30秒
	// // 需要执行的代码
	// buttonBatteryShow.performClick();//按钮被点击的API
	// }
	// };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.setTitle("众和诚内部专用电池检测统计APP V1.0   运行过程中请保持此界面始终显示");//标题栏显示
		textViewLevel = (TextView) findViewById(R.id.textViewBattery);
		ListViewBattery5 = (ListView) findViewById(R.id.ListViewBattery5);
		// 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);// 立即调用
	}
}

 

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="" />


    <ListView
      android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         android:id="@+id/ListViewBattery5" 
         android:layout_below="@id/textViewBattery"
         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>

demo下载

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值