Monday, May 21, 2012 : Article > Android User : Register | Login
บทความ
Webboard
วีดีโอ
บทความจากเพื่อนๆ Guru
15
ตัวอย่างการตรวจสอบระดับแบตเตอรี่ บน Android

1.สร้างโปรเจค Android ใช้ชื่อว่า AndroidBattery


2.เปิด file main.xml


จากนั้นใส่โค้ดดังนี้
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="@string/hello"
 />
<TextView
 android:id="@+id/batterylevel"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Battery Level:"
 />
</LinearLayout>

ผลลัพธ์ที่ได้


3.เปิด file AndroidBattery.java


แล้วใส่โค้ดดังนี้
 

package th.co.bighead.exsample.AndroidBattery;

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

public class AndroidBattery extends Activity {

private TextView batteryLevel;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
 
     batteryLevel = (TextView)findViewById(R.id.batterylevel);
     this.registerReceiver(this.myBatteryReceiver,
       new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
 }

 private BroadcastReceiver myBatteryReceiver
 = new BroadcastReceiver(){

 @Override
 public void onReceive(Context arg0, Intent arg1) {
  // TODO Auto-generated method stub
  int bLevel = arg1.getIntExtra("level", 0);

  batteryLevel.setText("Battery Level: "
    + String.valueOf(bLevel) + " %");
 }
 
 };
}


4.รันโปรแกรม

Post Rating

Comments

There are currently no comments, be the first to post one.

Post Comment

Only registered users may post comments.
Home | Article | Webboard | Video | Blog | Showcase | News
Copyright 2010 by devguru.mobi