(1)定义广播接收,显示电池电量—-MyBatteryInfoBroadcastReceiver
package tedu.cn.phoneservice;
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 MyBatteryInfoBroadcastReceiver 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", 100); //构造提示框
Dialog dialog = new AlertDialog.Builder(context)
.setTitle("电池电量")
.setMessage(
"电池电量为:" + String.valueOf(level * 100 / scale)
+ "%")
.setNegativeButton("关闭",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
}).create();
//别忘记显示
dialog.show();
}
}
}
(2)主程序
package tedu.cn.phoneservice;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
// TODO Auto-generated method stub
textView=(TextView) findViewById(R.id.tv);
textView.setOnClickListener(this);
}
@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;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
MyBatteryInfoBroadcastReceiver receiver=new MyBatteryInfoBroadcastReceiver();
IntentFilter filter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED) ;
registerReceiver(receiver, filter) ;
}
}
(3)TextView可点击 布局
<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"
tools:context=".MainActivity" >
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="92dp"
android:clickable="true"
android:text="获得电池电量" />
</RelativeLayout>
(4)运行