首页 > 代码库 > 特殊广播接收者

特殊广播接收者

比如操作特别频繁的广播事件 屏幕的锁屏和解锁 电池电量的变化 这样的广播接收者在清单文件里面注册无效
 
import android.os.Bundle;import android.app.Activity;import android.content.IntentFilter;import android.view.Menu;public class MainActivity extends Activity {    private ScreenReceiver screenReceiver;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                                        /* <receiver android:name="com.itheima.screen.ScreenReceiver">         <intent-filter >             <action android:name="android.intent.action.SCREEN_OFF"/>             <action android:name="android.intent.action.SCREEN_ON"/>         </intent-filter>     </receiver>*/             //[1]动态的去注册屏幕解锁和锁屏的广播        screenReceiver = new ScreenReceiver();        //[2]创建intent-filter对象        IntentFilter filter = new IntentFilter();        //[3]添加要注册的action        filter.addAction("android.intent.action.SCREEN_OFF");        filter.addAction("android.intent.action.SCREEN_ON");        //[4]注册广播接收者        this.registerReceiver(screenReceiver, filter);                    }            @Override    protected void onDestroy() {        //当activity销毁的时候  取消注册广播接收者        unregisterReceiver(screenReceiver);                super.onDestroy();    }    }

 

import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class ScreenReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        //[1]获取到当前广播的事件类型        String action = intent.getAction();        //[2]对当前广播事件类型做一个判断                if ("android.intent.action.SCREEN_OFF".equals(action)) {                        System.out.println("屏幕锁屏了");        }else if ("android.intent.action.SCREEN_ON".equals(action)) {                        System.out.println("说明屏幕解锁了~~~");        }                            }}


当activity销毁的时候 取消注册广播接收者
09-08 07:25:42.239: E/ActivityThread(2173): Activity com.itheima.screen.MainActivity has leaked IntentReceiver com.itheima.screen.ScreenReceiver@b6486088 that was originally registered here. Are you missing a call to
 unregisterReceiver()?
 
 

特殊广播接收者