android四大组件之Service 注册广播接收者

广播的注册一共有两种,一种就是用清单文件注册,还有另外一种就是用代码注册,代码注册比较灵活,可以在需要的时候注册,不需要的时候解除注册

用服务注册广播首先要开启服务,

然后在服务oncreate方法里注册广播,在ondestory方法里解除注册就可以了

package com.example.zhuceBroadcast;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MyActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    private Intent intent;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        intent = new Intent(this,RegistService.class);
        findViewById(R.id.startservie).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startService(intent);
            }
        });
        findViewById(R.id.stopservice).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopService(intent);
            }
        });
    }
}
package com.example.zhuceBroadcast;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

/**
 * Created by Administrator on 2015/11/17 0017.
 */
public class RegistService extends Service {
    MyReceiver myReceiver;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        //拿到广播接收者对象

        myReceiver = new MyReceiver();
        //拿到intentfilter
        IntentFilter filter = new IntentFilter();
        //屏幕开启和关闭
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        //注册
        registerReceiver(myReceiver, filter);
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(myReceiver);
    }
}
package com.example.zhuceBroadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * Created by Administrator on 2015/11/17 0017.
 */
public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(Intent.ACTION_SCREEN_ON.equals(action)){
            Toast.makeText(context,"屏幕开启",Toast.LENGTH_LONG).show();
        }else if (Intent.ACTION_SCREEN_OFF.equals(action)){
            Toast.makeText(context,"屏幕关闭",Toast.LENGTH_LONG).show();
        }
    }
}
原文地址:https://www.cnblogs.com/84126858jmz/p/4970972.html