码迷,mamicode.com
首页 > 其他好文 > 详细

特殊广播接收者

时间:2016-10-13 23:41:30      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

比如操作特别频繁的广播事件 屏幕的锁屏和解锁 电池电量的变化 这样的广播接收者在清单文件里面注册无效
 
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()?
 
 

特殊广播接收者

标签:

原文地址:http://www.cnblogs.com/xufengyuan/p/5958375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!