安卓:广播BroadcastReceiver的使用

一。最简单的静态注册广播

安卓:广播BroadcastReceiver的使用_第1张图片

1.创建一个继承BroadcastReceiver的类(广播的接收者)

2.在清单文件中注册广播:

3.主逻辑代码文件中创建一个Intent,然后发送广播:   sendBroadcast(intent);


主逻辑代码文件:

package com.example.day21_broadreceiver;

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

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


   public void send(View v)
   {
	   Intent intent=new Intent(MainActivity.this,MyBroad.class);
	  
	   sendBroadcast(intent);
   }
    
}

主布局文件:



    


广播接收方:

package com.example.day21_broadreceiver;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.widget.Toast;

public class MyBroad extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		Toast.makeText(context, "您有新的消息",0).show();
	}

}

清单文件中的标签内:

              android:name="com.example.day21_broadreceiver.MyBroad">

                                            <完>




二。隐式意图实现的发送广播,并给(静态注册的)广播设置优先级

安卓:广播BroadcastReceiver的使用_第2张图片


1.创建两个继承BroadcastReceiver的类,用来接收广播

2.清单文件中注册广播,并设置意图和优先级,添加动作:

        
           
                 
           

       

3.主逻辑代码中创建Intent,设置动作,传送内容,发送广播

4.继承BroadcastReceiver的类中接收广播内容



逻辑代码文件:

package com.example.day21_broadreceiver2;

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

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void send(View v)
    {
    	Intent intent=new Intent();
    	intent.putExtra("str","您好");
    	intent.setAction("com.wsx");
    	sendBroadcast(intent);
    }

    
}

主布局文件:



    

继承 BroadcastReceiver 的类 (里面内容一样,这里只写一个):

package com.example.day21_broadreceiver2;

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

public class BoradReceiver1 extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		String str=intent.getStringExtra("str");
		Toast.makeText(context, "==000=="+str, 0).show();
		
	}

}

清单文件里标签中:

                   android:name="com.example.day21_broadreceiver2.BoradReceiver2">
           
               
           

       
                    android:name="com.example.day21_broadreceiver2.BoradReceiver3">
           
               
           

       

                                                                              <完>


三。动态注册广播

安卓:广播BroadcastReceiver的使用_第3张图片



1.创建两个继承BroadcastReceiver的类,用来接收广播

2.主逻辑代码中,得到继承BroadcastReceiver的类的对象:    BoradReceiver1 receiver1=new BoradReceiver1();

3.主逻辑代码中onCreate方法里创建意图过滤,设置动作,注册广播:

        IntentFilter filter=new IntentFilter();
        filter.addAction("mars.wsx");
        registerReceiver(receiver1, filter);

4.主逻辑代码中,按钮事件里隐式意图发送广播

5.主逻辑代码中onStop方法里可取消广播注册:        unregisterReceiver(receiver1);



主逻辑代码文件:

package com.example.day21_broadreceiver2;

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

public class MainActivity extends Activity {

	BoradReceiver1 receiver1=new BoradReceiver1();
    BoradReceiver2 receiver2=new BoradReceiver2();
    BoradReceiver3 receiver3=new BoradReceiver3();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //创建意图过滤
        IntentFilter filter=new IntentFilter();
        filter.addAction("mars.wsx");
        registerReceiver(receiver1, filter);
        registerReceiver(receiver2, filter);
        registerReceiver(receiver3, filter);
    }
    @Override
    protected void onStop() {
    	super.onStop();
    	//取消广播注册
    	unregisterReceiver(receiver1);
    	unregisterReceiver(receiver2);
    	unregisterReceiver(receiver3);
    }
    public void send(View v)
    {
    	Intent intent=new Intent();
    	intent.putExtra("str","您好");
    	intent.setAction("mars.wsx");
    	sendBroadcast(intent);
    }
    
    
}



布局文件:



    

继承BroadcastReceiver的类文件:

package com.example.day21_broadreceiver2;

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

public class BoradReceiver1 extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		String str=intent.getStringExtra("str");
		Toast.makeText(context, "==000=="+str, 0).show();
		
	}

}

                                                                       <完>



前3种都是发送普通广播,不能中断:sendBroadcast();

发送有序广播可以中断:sendOrderedBroadcast();

四。发送有序广播及广播截断

安卓:广播BroadcastReceiver的使用_第4张图片安卓:广播BroadcastReceiver的使用_第5张图片安卓:广播BroadcastReceiver的使用_第6张图片安卓:广播BroadcastReceiver的使用_第7张图片



1.主逻辑代码文件按钮的监听事件中创建隐式Intent,设置动作,发送有序广播

2.创建3个继承BroadcastReceiver的类,都接收广播,弹出toast

3.在清单文件中注册广播,添加意图并分别设置优先级,1最高,3第二,2最低,设置动作

4.继承BroadcastReceiver的类1中写个通知,当收到广播时弹出通知

5.继承BroadcastReceiver的类3中添加一个中断广播的操作

6.写个Activity用作打开通知的详情页,取消通知

7.清单文件中注册Activity设置动作及动作的描述                                                                        隐式意图时广播的注册不需要动作描述,但类不行



主逻辑代码文件:

package com.example.day21_broadreceiver4;

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

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
    }
    public void send(View v)
    {
    	Intent intent=new Intent();
    	intent.putExtra("str","像疯了一样");
    	intent.setAction("hello.wsx");
    	sendOrderedBroadcast(intent, null);
    }
}


主布局文件:



    

第一个继承BroadcastReceiver的类文件:

package com.example.day21_broadreceiver4;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.widget.Toast;

public class MyBoradReceiver1 extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		String s=intent.getStringExtra("str");
		Toast.makeText(context,"==1111:优先级最高=="+s, 0).show();
		NotificationCompat.Builder builder=new NotificationCompat.Builder(context);
		builder.setContentTitle("来广播了");
		builder.setContentText("广播内容:"+s);
		builder.setSmallIcon(R.drawable.ic_launcher);
		builder.setWhen(System.currentTimeMillis());
		
		Intent in=new Intent();
		in.setAction("second.com");
		PendingIntent pi=PendingIntent.getActivity(context, 1, in, PendingIntent.FLAG_ONE_SHOT);
		builder.setContentIntent(pi);
		
		NotificationManager manager=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		manager.notify(1,builder.build());
					
	}

}


第二个继承BroadcastReceiver的类文件:

package com.example.day21_broadreceiver4;

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

public class MyBoradReceiver2 extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		String s=intent.getStringExtra("str");
		Toast.makeText(context,"==2222:优先级最低=="+s, 0).show();
		
	}

}


第三个继承BroadcastReceiver的类文件:

package com.example.day21_broadreceiver4;

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

public class MyBoradReceiver3 extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		String s=intent.getStringExtra("str");
		Toast.makeText(context,"==3333:优先级第二=="+s, 0).show();
		//中断广播,据优先级应是,1收到广播后,3收,最后2收,由于3发出了中断操作,即2不会收到广播
		abortBroadcast();
	}

}


第二个Activity逻辑代码文件:

package com.example.day21_broadreceiver4;

import android.os.Bundle;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.view.Menu;

public class SecondActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second);
		NotificationManager manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		manager.cancel(1);
	}
}

第二个Activity布局文件:



    




清单文件中添加:

        
            
                
            
        
        
            
                
            
        
        
            
                
            
        

        
            
                
                
            
        
                                                                                                                                                                 <完>



以下是系统广播:

五。系统广播----拨打电话

安装APP后当拨打电话时弹出toast如下:图中黄色圈的部分

安卓:广播BroadcastReceiver的使用_第8张图片



1.创建一个继承BroadcastReceiver的类,获取打电话时电话号:

                Bundle bundle=intent.getExtras();
                String num=bundle.getString(Intent.EXTRA_PHONE_NUMBER);

2.清单文件中添加允许拨打电话的权限,然后注册广播,添加意图过滤,设置拨打电话的系统动作

                              权限:   

                              动作: 


继承BroadcastReceiver的类文件:

package com.example.day21_broad_call;

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

public class MyBoradReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		if(intent!=null)
		{
			Bundle bundle=intent.getExtras();
			String num=bundle.getString(Intent.EXTRA_PHONE_NUMBER);
			Toast.makeText(context, "拨打的电话是:"+num, 1).show();
		}
		
	}

}

清单文件添加:


            
                
                
            
        

及权限:
	

                                                                                                                                                            <完>



六。系统广播----接听,挂断电话的状态

   安卓:广播BroadcastReceiver的使用_第9张图片                 安卓:广播BroadcastReceiver的使用_第10张图片   


1.创建一个继承BroadcastReceiver的类

2.得到电话管理者对象,电话状态,根据状态判断

3.清单文件中添加读取电话状态的权限,注册广播,添加意图过滤,设置系统电话状态的动作


继承BroadcastReceiver的类文件:

package com.example.day21_broad_callstate;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class MyBroadReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		//得到电话管理者对象
		TelephonyManager manager=(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		//得到电话状态
		int state=manager.getCallState();
		//得到上个Activity附带的额外数据
		Bundle bundle=intent.getExtras();
		//获取当前拨打电话的号码
		String num=bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
		switch(state)
		{
		//挂断状态
		case TelephonyManager.CALL_STATE_IDLE:
			Toast.makeText(context, "挂断", 1).show();
			break;
		//接听状态
		case TelephonyManager.CALL_STATE_OFFHOOK:
			Toast.makeText(context, "接听", 1).show();
			break;
		//响铃状态
		case TelephonyManager.CALL_STATE_RINGING:
			Toast.makeText(context, "响铃", 1).show();
			break;
		}
				
	}

}

清单文件中添加:

      权限:   

      广播的:

                   android:name="com.example.day21_broad_callstate.MyBroadReceiver">
           
               
           

       

                                                                                                            <完>



七。系统广播----短信

安卓:广播BroadcastReceiver的使用_第11张图片

1.创建一个继承BroadcastReceiver的类

2.获得Intent附带的数据,得到收到的短信。。。。

3.清单文件中添加允许接收短信的权限,注册广播,添加意图过滤,动作为接收短信广播接收器


继承BroadcastReceiver的类文件:

package com.example.day21_broad_smsinforation;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class MyBroadReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle=intent.getExtras();
		//得到收到的短信
		Object pduses[]=(Object[]) bundle.get("pdus");
		for (Object pdus : pduses) {
			byte pdu[]=(byte[]) pdus;
			SmsMessage sms=SmsMessage.createFromPdu(pdu);
			//得到发送短信的号码
			String num=sms.getOriginatingAddress();
			//得到短信的内容
			String body=sms.getMessageBody();
			//得到短信的时间
			long time=sms.getTimestampMillis();
			SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
			String t=sf.format(new Date(time));
			Toast.makeText(context, "短信来自:"+num+"\n短信内容:"+body+"\n时间:"+t, 1).show();
			
		}
		
		
	}

}

清单文件中添加:


   

        
            
                
                
            
        

                                                                                                                                                                         <完>


八。系统广播----电池电量



逻辑代码文件:

package com.example.day21_broad_battery;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;

public class MainActivity extends Activity {

	MyBroadReceiver receiver=new MyBroadReceiver();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //创建广播的意图过滤,检测电源变化
        //参数:action标记,据此检测电源变化
        IntentFilter filter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(receiver, filter);
    
    
    }
   
}

继承 BroadcastReceiver 的类文件:

package com.example.day21_broad_battery;

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

public class MyBroadReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction()))
		{
			//获取电量等级
			int level=intent.getIntExtra("level", 0);
			//获取总电量
			int total=intent.getIntExtra("scale", 0);
			//计算当前电量
			int current=(level*100)/total;
			Toast.makeText(context, "总电量:"+total+"\n当前电量:"+current, 1).show();
			
		}
		
	}

}

清单文件中:

   


九。系统广播----网络连接情况


逻辑代码文件:

package com.example.day21_broad_intenet;

import android.net.ConnectivityManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.IntentFilter;
import android.view.Menu;

public class MainActivity extends Activity {

	MyBroadReceiver receiver=new MyBroadReceiver();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IntentFilter filter=new IntentFilter();
        //检测网络变化的
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);
    }
    
}

继承BroadcastReceiver的类文件:

package com.example.day21_broad_intenet;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

public class MyBroadReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		//得到网络管理者对象
		ConnectivityManager manager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info=manager.getActiveNetworkInfo();
		if(info==null)
		{
			Toast.makeText(context, "网络异常", 0).show();	
		}
		else
		{
			if(info.isConnected())
			{
				Toast.makeText(context, "网络连接正常", 0).show();	
			}
			else
			{
				Toast.makeText(context, "网络连接超时", 0).show();	
			}
		}
	}

}

清单文件中:

   

你可能感兴趣的:(安卓)