Android发送和接收自定义Broadcast


BroadcastReceiver意为广播接收,通过它可以实现进程间通信也可以实现进程内部进行通信,对于广播的消息我们只处理感兴趣的消息,可以接收系统的广播(短信、开机)也可以接收自定义的广播,但都需要注册才能接收,注册的方式又分两种,一是在AndroidMainfest.xml中注册,二是在代码中注册。

BroadcastReceiver是一个抽象的类,我们需要继承它才能创建对象

创建一个类ReceiveMsg.java继承BroadcastReceiver,并定义两个自定义的消息

package com.example.receivermsg;

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

public class ReceiverMsg extends BroadcastReceiver {

	//定义两个自定义的消息
	public static final String MSG = "com.example.msg";
	public static final String REG_MSG = "com.example.reg.msg";
	/**
	 * 接收消息处理
	 */
	@Override
	public void onReceive(Context arg0, Intent arg1) {
		// TODO Auto-generated method stub
		if(arg1.getAction().equals(MSG)){
			System.out.println(MSG);
		}
		else if(arg1.getAction().equals(REG_MSG)){
			System.out.println(REG_MSG);
		}
	}

}
在AndroidMainfest.xml文件中声明

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcastdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.broadcastdemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- 定义Broadcast Receiver 指定监听的Action -->
    	<receiver android:name="com.example.receivermsg.ReceiverMsg">
             <!-- 注册自定义的消息 -->
              <intent-filter >
    	        <action android:name="com.example.reg.msg"/>
    	    </intent-filter>
   	 	</receiver>
   	 	
    </application>

    <!-- 声明接收消息的权限 -->
    <uses-permission android:name="android.permission.RECEIVE_SMS" >
    </uses-permission>

</manifest>

在Activity中添加两个按钮监听器发送消息用

package com.example.broadcastdemo;

import com.example.receivermsg.ReceiverMsg;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

	private Button sendMsg = null;
	private Button sendReg = null;
	private ReceiverMsg receiver = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		sendMsg = (Button) findViewById(R.id.sendMsg);
		sendReg = (Button) findViewById(R.id.sendRegMsg);
		sendMsg.setOnClickListener(this);
		sendReg.setOnClickListener(this);

		// 生成一个BroiadcastReceiver对象
		receiver = new ReceiverMsg();
		// 生成一个IntentFilter对象
		IntentFilter filter = new IntentFilter();
		// 为IntentFilter添加一个Action
		filter.addAction(ReceiverMsg.MSG);
		// 将BroadcastReceiver对象注册到系统当中
		registerReceiver(receiver, filter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * 按钮监听
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		int id = arg0.getId(); // 用来区分点击的是哪个按钮
		if (id == R.id.sendMsg) {
			Intent intent = new Intent();
			intent.setAction(ReceiverMsg.MSG);
			sendBroadcast(intent);
			System.out.println("send own msg");
		} else if (id == R.id.sendRegMsg) {
			Intent intent = new Intent();
			intent.setAction(ReceiverMsg.REG_MSG);
			sendBroadcast(intent);
			System.out.println("send reg msg");
		}
	}

}
在onReceive中接收到感兴趣的消息就可以根据需要进行处理,比如更新播放进度、更新时间等操作。

样例源码

点击打开链接

你可能感兴趣的:(android)