开机关机广播和电量变化广播

广播的使用步骤:
1.注册(在AndroidManifest.xml中声明receiver或者手动调用registerReceiver方法);
2.声明权限;
3.实现广播;
4.取消注册(和注册需要一对一调用);

注册:

mContext.registerReceiver(mVoltageCheck, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
mContext.registerReceiver(ShutdownReceiver, new IntentFilter(Intent.ACTION_SHUTDOWN));

取消注册:

mContext.unregisterReceiver(mVoltageCheck);
mContext.unregisterReceiver(ShutdownReceiver);

声明权限:

<uses-permission android:name="android.permission.SHUTDOWN"/>

实现:
关机广播

private BroadcastReceiver ShutdownReceiver = new BroadcastReceiver() {
        final static String TAG = "ShutdownReceiver";
        final static String onReceive = "onReceive";
        final static String ACTION = "android.intent.action.ACTION_SHUTDOWN";//截取关机事件

   @Override
    public void onReceive(Context arg0, Intent arg1) {
            // TODO Auto-generated method stub
            Log.d(TAG,onReceive);
            if (arg1.getAction().equals(ACTION)) {
                Log.e(TAG,"imageCount = "+imageCount);
                stop = false;
            }
            Log.e(TAG,ACTION);
        }
    };

监测电量广播:

private BroadcastReceiver mVoltageCheck = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
                // 电压 电池电量
                Log.i(TAG,"ACTION_BATTERY_CHANGED");
                int level = intent.getIntExtra("level", -1);
                int voltage = intent.getIntExtra("voltage", 0);
                Log.i(TAG,"level = "+level);
                Log.i(TAG,"voltage = "+voltage);
                if(voltage == 0){
                    ......
                }
            }
        }
    };

开机广播:
权限

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

注册:

<receiver android:name="com.pax.reboot.BootBroadcastReceiver">
<intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED"/   >
</intent-filter>
</receiver>

实现:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BootBroadcastReceiver extends BroadcastReceiver {
final static String TAG = "BootBroadcastReceiver";
final static String ACTION = "android.intent.action.BOOT_COMPLETED";

@Override
public void onReceive(Context arg0, Intent arg1) {
    // TODO Auto-generated method stub
Log.e(TAG,"onReceive");                if(arg1.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent intent = new Intent(arg0, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
arg0.startActivity(intent);
        }
    }
}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

开机关机广播和电量变化广播

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭