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(); } } } </pre><br />
2.定義布局管理器--main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns: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> </pre><br />
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); } } } </pre><br />
本文由用戶 cymt 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!