Android四大组件之四:BroadcastReceiver 广播接收器

1.BroadcastReceiver 广播接收器 (Android四大组件之一)
  [1]用途:接收广播。可以接收系统广播,可以接收其它应用程序的广播,可以接收其它组件的广播。
  [2]生命周期:只有十秒种,不能在广播接收器中做耗时的操作。
  [3]注意:如果接收系统广播,需要添加权限。
           接收广播的种类在清单文件中设置
            <intent-filter >
                <!-- 设置广播接收器可以接收开机广播 -->
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
  
package com.farsight.broadcastreceiver;

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

public class MyReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		String info = intent.getStringExtra("info");
		Toast.makeText(context, "收到广播:"+info, Toast.LENGTH_SHORT).show();
		
		Intent intentA = new Intent();
		intentA.setClass(context, Android_39_BroadcastReceiverActivity.class);
		//在非Activity组件中启动活动,需要加标记
		intentA.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intentA);
	}

}

package com.farsight.activityandservice;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class Android_41_ActivityAndServiceActivity extends Activity implements OnClickListener {
	TextView tv;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Activity组件接收Service组件发送的广播
		// Service 向 Activity 发送广播

		
		//在当前activity对象上注册广播接收器
		this.registerReceiver(myReceiver, new IntentFilter(
				"com.farsight.activityandservice.activity"));
		
		
		findViewById(R.id.button1).setOnClickListener(this);
		tv = (TextView) findViewById(R.id.textView1);
	}

	MyReceiver myReceiver = new MyReceiver();

	class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			int count = intent.getIntExtra("count", -1);
			tv.setText(String.valueOf(count));
		}

	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//注销广播接收器
		this.unregisterReceiver(myReceiver);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		intent.setClass(this, MyService.class);
		startService(intent);
	}
}
package com.farsight.activityandservice;

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

public class MyService extends Service implements Runnable {

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		new Thread(this).start();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		int count = 0;
		//每隔一秒钟,向活动发送数据
		
		while(true){
			count++;
			
			Intent intent = new Intent();
			intent.setAction("com.farsight.activityandservice.activity");
			intent.putExtra("count", count);
			sendBroadcast(intent);
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}



2.Android多媒体编程
  [1]多媒体文件:图片文件 png jpg gif
                 音频     mp3 ogg mid
                 视频     mp4 3gp
  [2]音乐播放器  MediaPlayer  --- 播放音乐
                 SoundPlayer  --- 播放音效
  [3]MediaPlayer                                             从sdcard载入音乐文件
                 MediaPlayer.create(this, R.raw.music_01)    从res/raw下载入音乐文件
                 start()                                     播放音乐

                 pause()                                     暂停音乐

package com.farsight.mediaplayer;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class Android_37_MediaPlayerActivity extends Activity implements OnClickListener, OnSeekBarChangeListener {
    
	TextView tvSize;
	TextView tvCurrent;
	
	SeekBar seekBar;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);
        
        tvSize = (TextView) findViewById(R.id.textView1);
        tvCurrent = (TextView) findViewById(R.id.textView2);
        seekBar = (SeekBar) findViewById(R.id.seekBar1);
        
        seekBar.setOnSeekBarChangeListener(this);
        
        this.registerReceiver(receiver, new IntentFilter("receive music data"));
    }

    MyReceiver receiver = new MyReceiver();
    class MyReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			
			int size = intent.getIntExtra("size", -1);
			if(size != -1)
			{
				tvSize.setText(timeFormat(size));
				seekBar.setMax(size);
			}
			
			int current = intent.getIntExtra("current", -1);
			tvCurrent.setText(timeFormat(current));
			seekBar.setProgress(current);
			
		}
    	
    }
    
    Intent intent = new Intent();
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId() == R.id.button1){
			intent.setClass(this, PlayMusicService.class);
			intent.putExtra("control", "play");
			startService(intent);
		}
		else if(v.getId() == R.id.button2){
			intent.setClass(this, PlayMusicService.class);
			intent.putExtra("control", "pause");
			startService(intent);
		}
		else if(v.getId() == R.id.button3){
			//退出音乐播放器
			//暂停音乐并回收音乐资源
			//关闭子线程
			intent.setClass(this, PlayMusicService.class);
			intent.putExtra("control", "destroy");
			startService(intent);
			//销毁activity
			finish();
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		this.unregisterReceiver(receiver);
	}
	
	//将毫秒转换为分钟显示
	private String timeFormat(int millionSecond){
		String format = "";
		int minutes = millionSecond/1000/60;
		if(minutes < 10){
			format += "0"+minutes;
		}else{
			format += minutes;
		}
		format += ":";
		int second = millionSecond/1000%60;
		if(second < 10){
			format += "0"+second;
		}else{
			format += second;
		}
		return format;
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		intent.setClass(this, PlayMusicService.class);
		intent.putExtra("control", "pause");
		startService(intent);
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		intent.setClass(this, PlayMusicService.class);
		intent.putExtra("control", "seekTo");
		//
		intent.putExtra("target", seekBar.getProgress());
		startService(intent);
	}
}
package com.farsight.mediaplayer;

import java.io.IOException;

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

public class PlayMusicService extends Service implements Runnable,
		OnCompletionListener {

	// 音乐播放器对象
	// 控制音乐播放
	MediaPlayer mediaPlayer;
	boolean isRun;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();

		// 当前音乐播放时间
		// mediaPlayer.getCurrentPosition();

		// 改变音乐当前的播放位置,传入的参数为时间值
		// mediaPlayer.seekTo(mediaPlayer.getDuration()/2);

		nextMusic();
		
		isRun = true;
		new Thread(this).start();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub

		String control = intent.getStringExtra("control");
		if (control.equals("play"))
			mediaPlayer.start();
		else if (control.equals("pause"))
			mediaPlayer.pause();
		else if (control.equals("seekTo")) {
			mediaPlayer.seekTo(intent.getIntExtra("target", 0));
			mediaPlayer.start();
		} else if (control.equals("destroy")) {
			mediaPlayer.stop();
			mediaPlayer.release(); // 回收音乐资源
			isRun = false; // 关闭线程
		}
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

		while (isRun) {
			// 检测当前音乐是否正在播放
			if (mediaPlayer.isPlaying()) {

				int currentTime = mediaPlayer.getCurrentPosition();
				Intent intent = new Intent();
				intent.setAction("receive music data");
				intent.putExtra("current", currentTime);
				sendBroadcast(intent);
			}

			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	// 当音乐播放完毕时,调用该方法
	@Override
	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub
		nextMusic();
		mediaPlayer.start();
	}

	String paths[] = {"/sdcard/abc.mp3", "/sdcard/music_01.MID"};
	int index = 0;
	private void nextMusic() {
		// 从内部资源文件夹载入音乐资源
		// mediaPlayer = MediaPlayer.create(this, R.raw.music_01);
		// 从sdcard载入音乐资源
		mediaPlayer = new MediaPlayer();
		try {
			mediaPlayer.setDataSource(paths[index++%paths.length]);
			mediaPlayer.prepare();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// //设置循环播放
		// mediaPlayer.setLooping(true);

		// 得到音乐的总时长,以毫秒为单位
		int size = mediaPlayer.getDuration();
		Intent intent = new Intent();
		intent.putExtra("size", size);
		intent.setAction("receive music data");
		sendBroadcast(intent);

		// 监听当前音乐是否播放完毕
		mediaPlayer.setOnCompletionListener(this);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值