Android BroadcastReceiver

  

        BroadcastReceiver,用于异步接收广播Intent,广播Intent是通过调用Context.sendBroadcast()发送、BroadcastReceiver()接收。

      广播Intent的发送是通过调用Context.sendBroadcast()、Context.sendOrderedBroadcast()、Context.sendStickyBroadcast()来实现的。通常一个广播Intent可以被订阅了此Intent的多个广播接收者所接收,广播接收者和JMS中的Topic消息接收者很相似。

    广播接收器没有用户界面,但是它可以为它们接收到信息启动一个Activity或者使用NotificationManager来通知用户.

   BroadcastReceiver 接收广播方式:

   1.Normal Broadcast(正常广播), 用context.sendBroadcast()发送是完全异步的,他们都运行在一个未定义的的顺序,通常是在同一时间,这样会更有效,但意味着reciiver不能使用所包含的结果或者终止的API;

 2. Orderbroadcast(有序广播),用context.sendOrsderBroadcast()发送每次被发送到一个receiver。所谓有序就是每个recever执行后可以传播到下一个recever,也可以完全终止传播...---不传给其他recever。而recever运行的顺序可以通过matched intent—filter里面的android:priority来控制,当priority

 优先级相同的时候,Receiver以任意的顺序运行;

     主Activity    PlayMusicRecevicer  点击按钮 把启动的服务 通过sendBroadcast(intent)广播出去;

    

package com.example.myservice;

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

public class PlayMusicRecevicer extends Activity implements OnClickListener{
     private Button play,stop,pause,exit,close;
     private Intent intent;
     private static final String TAG="PlayMusicRecevicer";
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int op=-1;
		Log.i(TAG, "....play");
		intent=new Intent("com.android.service");
		switch (v.getId()) {
		case R.id.play:
			op=1;
			break;
		case R.id.stop:
			op=2;
			break;
		case R.id.pause:
			op=3;
			break;
		case R.id.exit:
			this.finish();
			break;
		case R.id.close:
			op=4;
			break;
		default:
			break;
		}
		Bundle bundle=new Bundle();
		bundle.putInt("op", op);
		intent.putExtras(bundle);
		sendBroadcast(intent);
	}
   //第二种注册方式..
  /*  @Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		receiver=new MuscReceiver();
		IntentFilter filter =new IntentFilter();
		filter.addAction("com.android.service");
		this.registerReceiver(receiver, filter);
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		this.unregisterReceiver(receiver);
	}*/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.playmusic);
		
		play=(Button)findViewById(R.id.play);
		stop=(Button)findViewById(R.id.stop);
		pause=(Button)findViewById(R.id.pause);
		exit=(Button)findViewById(R.id.exit);
		close=(Button)findViewById(R.id.close);
		
		play.setOnClickListener(this);
		stop.setOnClickListener(this);
		pause.setOnClickListener(this);
		exit.setOnClickListener(this);
		close.setOnClickListener(this);
				
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(intent!=null){
			stopService(intent);
		}
	}

}

   MusicReceiver 继承BroadcastReceiver 接受广播出来的信息...

    

package com.android.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class MuscReceiver extends BroadcastReceiver {
	private static final String TAG="MuscReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if(intent!=null){
			Log.i(TAG, "...MuscReceiver");
			Bundle bundle=intent.getExtras();
			Intent it=new Intent(context,MusicReceiverService.class);
			it.putExtras(bundle);
			if(bundle!=null){
				int op=bundle.getInt("op");
				Log.i(TAG, "...op"+op);
				if(op==4){
					context.stopService(it);
				}else{
					context.startService(it);
				}
			}
			
		}
		
	}

}
     MusicReceiverService继承Service 并在配置文件中进行配置...

    

package com.android.service;

import java.io.IOException;

import com.example.myservice.R;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;

public class MusicReceiverService extends Service {
   private MediaPlayer mediaPlayer;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
		public void onCreate() {
			// TODO Auto-generated method stub
			super.onCreate();
			if(mediaPlayer==null){
				mediaPlayer=MediaPlayer.create(this, R.raw.burning);
				mediaPlayer.setLooping(false);
			}
			
		}
   @Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(mediaPlayer!=null){
			mediaPlayer.stop();
			mediaPlayer.release();
		}
	}
   @Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		if(intent!=null){
			Bundle bundle=intent.getExtras();
			if(bundle!=null){
				int op=bundle.getInt("op");
				switch (op) {
				case 1:
					 play();
					break;
				case 2:
					stop();
					
					break;
				case 3:
					pause();
					break;
				default:
					break;
				}
			}
			
		}
	}
   public void play(){
	   if(!mediaPlayer.isPlaying()){
		   mediaPlayer.start();
	   }
   }
   public void pause(){
	   if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
		   mediaPlayer.pause();
	   }
   }
   public void stop(){
	   if(mediaPlayer!=null){
		   mediaPlayer.stop();
		   
		   try {
			mediaPlayer.prepare();  // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数  
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   }
   }
}
     AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myservice"
    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.myservice.PlayMusicRecevicer"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>       
       <service 
           android:name="com.android.service.MusicReceiverService"
           android:enabled="true"
           android:exported="true">
           <intent-filter>
               <action android:name="com.android.service.musicReceiverService">
                   </action>
               </intent-filter>
       </service>
        <receiver android:name="com.android.service.MuscReceiver" >
            <intent-filter>
                <action android:name="com.android.service" >
                </action>
            </intent-filter>
        </receiver>
    </application>


</manifest>

      

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值