Android多媒体-播放多媒体时的前台服务

众所周知,一般我们将播放的逻辑都放入service当中,这样就能实现在后台继续播放音乐的功能。后台service被系统回收的概率相对来说比较低,但是这种情况也确实存在。

前台服务是那些被认为用户知道的并且在内存低的时候不允许系统杀死的服务。前台服务必须给状态栏提供一个通知,他被放到了“正在进行中(Ongoing)”标题之下,这就意味着直到这个服务被终止或从前台删除通知才能被解除。

例如,一个播放音乐的音乐播放器服务应该被设置在前台运行,因为用户明确的知道它们的操作。状态栏中的通知可能指明了当前的歌曲,并且用户启动一个跟这个音乐播放器交互的Activity。


要让你的服务在前台运行,需要调用startForeground()方法,这个方法需要两个参数:一个唯一标识通知的整数和给状态栏的通知,如:

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),System.currentTimeMillis());      
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),getText(R.string.notification_message), pendingIntent);       
startForeground(ONGOING_NOTIFICATION, notification);
要从前台删除服务,需要调用stopForeground()方法,这个方法需要一个布尔型参数,指示是否删除状态栏通知。这个方法不终止服务。但是,如果你终止了正在运行的前台服务,那么通知也会被删除。


注意:startForeground()和stopForeground()方法是在Android2.0(API Level 5)中引入的。为了在比较旧的平台版本中运行你的服务,你必须使用以前的setForeground()方法---关于如何提供向后的兼容性,请看startForeground()方法文档。

示例代码如下:

ForgroundService.java

import java.io.File;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;

public class ForgroundService extends Service {
	
	private static final int NOTIFICATION_ID = 100;
	private static final Uri mMusicUri = Uri.fromFile(new File("/sdcard/sound_file_1.mp3"));
	private MediaPlayer mMediaPlayer = null;
	
	public class ForgroundServiceBinder extends Binder {

		public void playMusic() {

			stopCurrentMediaPlayer();
			mMediaPlayer = MediaPlayer.create(getApplicationContext(), mMusicUri);
			mMediaPlayer.start();		
			
			String songName = "Test Music";
			// assign the song name to songName
			PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), ForgroundServiceActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
			Notification notification = new Notification();
			notification.tickerText = "Forground Service";
			notification.icon = R.drawable.icon;
			notification.flags |= Notification.FLAG_ONGOING_EVENT;
			notification.setLatestEventInfo(getApplicationContext(), "MusicPlayerSample", "Playing: " + songName, pi);
			startForeground(NOTIFICATION_ID, notification);//启动前台服务
			
		}

		public void stopMusic() {
			stopCurrentMediaPlayer();
			stopForeground(true);	//关闭前台服务
		}
	}
	
	private ForgroundServiceBinder mBinder = new ForgroundServiceBinder();
	
	@Override
	public IBinder onBind(Intent arg0) {		
		return mBinder;
	}
		

	@Override
	public void onDestroy() {
		stopCurrentMediaPlayer();
		super.onDestroy();
	}


	private void stopCurrentMediaPlayer() {
		if (mMediaPlayer != null) {
			mMediaPlayer.stop();
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
	}

}

ForgroundServiceActivity.java

import ForgroundService.ForgroundServiceBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;

public class ForgroundServiceActivity extends Activity {
	
	@Override
	protected void onDestroy() {
		unbindService(mServiceConnection);
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_forground_service);
		
		final Intent serviceIntent = new Intent(this, ForgroundService.class);
		
		//startService(serviceIntent);
		bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);
		
	}
	
	private ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder binder) {

			final ForgroundServiceBinder service = (ForgroundServiceBinder) binder;
					
			findViewById(R.id.start).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					service.playMusic();
				}
				
			});

			findViewById(R.id.stop).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					service.stopMusic();
				}
				
			});
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {				
		}
		
	};		

}

layout_forground_service.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Play" />

    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop" />

</LinearLayout>



Android多媒体-播放多媒体时的前台服务,布布扣,bubuko.com

Android多媒体-播放多媒体时的前台服务

上一篇:自学安卓开发


下一篇:LeetCode 689. Maximum Sum of 3 Non-Overlapping Subarrays