android-发送自定义广播

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangxuewei111/article/details/45480873

1.发送标准广播

1.在发送广播之前,我们还是需要先定义一个广播接收器来准备接收此广播。MyBroadcastReceiver.java
<span style="font-size:14px;">package com.king.broadcasttest;

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

public class MyBroadcastReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
	}

}</span><span style="font-size:18px;">
</span>
2.在AndroidManifest.xml中对这个广播接收器进行注册

<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.king.broadcasttest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name=".BootCompleteReceiver">
            <intent-filter>
                
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
            
            
        <strong></receiver>
          <receiver android:name=".MyBroadcastReceiver">
            <intent-filter>
                
                <action android:name="com.king.broadcasttest.MY_BROADCAST"/>
            </intent-filter>
            
            
        </receiver></strong>
        <activity
            android:name="com.king.broadcasttest.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>
    </application>

</manifest></span><span style="font-size:18px;">
</span>
3.activity_main.xml
<span style="font-size:14px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    
    <Button 
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="send Broadcast"
        />

</RelativeLayout></span><span style="font-size:18px;">
</span>
4.首先构建出了一个Intent对象,并把要发送的广播的值传入,然后调用了Context的sendBroadcast()方法将广播发送出去,这样所有监听com.example.broadcasttest.MY_BROADCAST这条广播的广播接收器就会收到消息。此时发出去的广播就是一条标准广播。MainActivity.java
<span style="font-size:14px;">package com.king.broadcasttest;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	private IntentFilter intentFilter;
	private NetworkChangeReceiver networkChangeReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		intentFilter = new IntentFilter();
		intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
		networkChangeReceiver = new NetworkChangeReceiver();
		registerReceiver(networkChangeReceiver, intentFilter);
		
		
		Button button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent("com.king.broadcasttest.MY_BROADCAST");
				sendBroadcast(intent);
			}
		});
		
		
		
	}
	class NetworkChangeReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			
			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
			if(networkInfo != null && networkInfo.isAvailable()){
				Toast.makeText(context, "network is available", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(context, "network is unavailable", Toast.LENGTH_SHORT).show();
			}
		}
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(networkChangeReceiver);
	}

}</span>

2.发送有序广播

广播是一种可以跨进程的通信方式,这一点从前面的接收系统广播的时候就可以看出来了,用此在我们应用程序内发出的广播,其他的应用程序应该也是可以收回的,为了验证这一点,我们需要再新建一个BroadcastTest2项目。
1.用于接收上一个demo的自定义广播。AnotherBroadcastReceiver.java
<span style="font-size:14px;">package com.king.broadcasttest2;

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

public class AnotherBroadcastReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Toast.makeText(context, "received in AnotherBroadcastReceiver", Toast.LENGTH_SHORT).show();
		//表示将这条广播截断,后面的广播接收器将无法再接收这条广播
		abortBroadcast();
	}

}</span><span style="font-size:18px;">
</span>
2.这里仍然是在广播接收器的onReceive()方法中弹出了一段文本信息。然后在AndroidManifest.xml中对这个广播接收器进行注册。
<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.king.broadcasttest2"
    android:versionCode="1"
    android:versionName="1.0" >
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <!-- </span><pre name="code" class="html"><span style="font-size:14px;"><strong>android:priority="100":有序广播的优先级</strong></span>
--> <receiver android:name=".AnotherBroadcastReceiver"> <intent-filter android:priority="100"> <action android:name="com.king.broadcasttest.MY_BROADCAST"/> </intent-filter> </receiver> <activity android:name="com.king.broadcasttest2.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> </application></manifest>
 
  
3.MainActivity.java
<span style="font-size:14px;">package com.king.broadcasttest2;


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

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent("com.king.broadcasttest.MY_BROADCAST");
			sendBroadcast(intent);</span>
<span style="font-size:14px;"><span style="white-space:pre">			</span>//发送有序广播
	</span><pre name="code" class="java"><span style="font-size:14px;">//	</span><span style="font-family: Arial, Helvetica, sans-serif;">			sendOrderedBroadcast(intent, null);</span>
}});}@Overridepublic 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;}}
 
   


4.可以看到,AnotherBroadcastReceiver同样接收的是com.king.broadcasttest.MY_BROADCAST这条广播。现在运行BroadcastTest2项目将这个程序安装到模拟器上,然后重新回到BroadcastTest项目的主界面,并点击一下SendBroadcast按钮,就会分别弹出两次提示信息。





猜你喜欢

转载自blog.csdn.net/wangxuewei111/article/details/45480873