Android--电池相关信息的获取
1.定义广播接收,显示电池信息--BatteryInfoBroadcastReceiver
package org.lxh.demo; import android.app.AlertDialog; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; public class BatteryInfoBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) { int level = intent.getIntExtra("level", 0); int scale = intent.getIntExtra("scale", 0); int voltage = intent.getIntExtra("voltage", 0); int temperature = intent.getIntExtra("temperature", 0); String technology = intent.getStringExtra("technology"); Dialog dialog = new AlertDialog.Builder(context) .setTitle("电池电量") .setMessage( "电池电量为:" + String.valueOf(level * 100 / scale) + "%\n" + "电池电压为:" + String.valueOf((float)voltage / 1000) + "v" + "\n电池类型为:" + technology + "\n" + "电池温度为:" + String.valueOf((float)temperature / 10) + "°C") .setNegativeButton("关闭", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { } }).create(); dialog.show(); } } }
2.定义布局管理器--main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/mybtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="获取电池电量" /> </LinearLayout>
3.定义Activity程序:
package org.lxh.demo; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Hello extends Activity { private Button mybtn = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 生命周期方法 super.setContentView(R.layout.main); // 设置要使用的布局管理器 this.mybtn = (Button) super.findViewById(R.id.mybtn); this.mybtn.setOnClickListener(new OnClickListenerImpl()); } private class OnClickListenerImpl implements OnClickListener { public void onClick(View v) { BatteryInfoBroadcastReceiver receiver = null; receiver = new BatteryInfoBroadcastReceiver(); IntentFilter filter = new IntentFilter( Intent.ACTION_BATTERY_CHANGED); Hello.this.registerReceiver(receiver, filter); } } }
在实际手机上运行效果如下:
源码下载地址:http://download.csdn.net/detail/yayun0516/8409715
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。