android开发 - Broadcast Receiver

一个电量监听的案例


//申请电池状态



//创建一个继承BroadcastReceiver的类
public class MyBroad extends BroadcastReceiver { 
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
int level = intent.getIntExtra("level", 0);
int total  = intent.getIntExtra("scale",100);
Toast.makeText(context, "当前电量:"+(level*100)/total+"%", Toast.LENGTH_SHORT).show();


}




//在activity中交互时和应用程序暂停时的监听
public class MainActivity extends Activity {
private MyBroad broad;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}


@Override
protected void onResume() { 
super.onResume();
broad = new MyBroad();
IntentFilter filerFilter =new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(broad, filerFilter);
}


@Override
protected void onPause() { 
super.onPause();
unregisterReceiver(broad);
}


}
























一个开机启动的程序案例




//申请启动权限
 


//注册一个接收者
 
           
               
               
           

       





//实现一个类继承广播
public class MyPower extends BroadcastReceiver { 
@Override
public void onReceive(Context context, Intent intent) {
Intent intent2 = new Intent(context,MainActivity.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);

}













你可能感兴趣的:(android)