activity_main.Xml
<LinearLayout 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" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="查看剩余电量" />
</LinearLayout>
BatteryReceiver .java类
package com.example.broadcastreceiver2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class BatteryReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// TODO Auto-generated method stub
if(action.equals(Intent.ACTION_BATTERY_CHANGED)){
int level = intent.getIntExtra("level", 0);
int scale = intent.getIntExtra("scale", 100);
Toast.makeText(context, "剩余电量:" +(level*100/scale)+"%",Toast.LENGTH_LONG).show();
}
}
}
MainActivity.java
package com.example.broadcastreceiver2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class BatteryReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// TODO Auto-generated method stub
if(action.equals(Intent.ACTION_BATTERY_CHANGED)){
int level = intent.getIntExtra("level", 0);
int scale = intent.getIntExtra("scale", 100);
Toast.makeText(context, "剩余电量:" +(level*100/scale)+"%",Toast.LENGTH_LONG).show();
}
}
}