Android基於Service服務的音樂播放

學習了Service與Activity的通信,此例則在通信的基礎上實現後臺音樂播放,即退出界面後仍然可以播放音頻。

 

maiin.xml文件內容如下,主要是界面佈局。

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

	<ImageButton android:layout_width="wrap_content" 
	android:src="@drawable/play1" 
	android:id="@+id/startplay" 
	android:layout_height="wrap_content">
	</ImageButton>
	<ImageButton android:layout_width="wrap_content" 
	android:src="@drawable/play3" 
	android:id="@+id/stopplay" 
	android:layout_height="wrap_content">
	</ImageButton>
	
	<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	    android:orientation="vertical"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent"
	    >	
		<TextView android:text="@string/myTextView1" 
		android:layout_width="wrap_content" 
		android:id="@+id/TextView01" 
		android:layout_height="wrap_content"
		android:textSize="25px"
		android:textColor="#ffffff"
		android:ellipsize="marquee"
		>
		</TextView>
		<TextView android:text="@string/myTextView2" 
		android:id="@+id/TextView02" 
		android:layout_width="wrap_content" 
		android:layout_height="wrap_content"
		android:textSize="20px"
		android:textColor="#ffffff"
		android:ellipsize="marquee">
		</TextView>
	</LinearLayout>
</LinearLayout>


string.xml文件內容如下,這個文件在國際化編程中很實用,可以實現多國語言符號的界面顯示。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, myMusicPlayer!</string>
    <string name="app_name">myMusicPlayer</string>
    <string name="myTextView1">甜蜜蜜</string>
    <string name="myTextView2">鄧麗君</string>
</resources>


 

AndroidManifest.xml文件內容如下:程序配置。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.demo.myMusicPlayer"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".myMusicPlayer"
                  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:enabled="true" android:name = ".MyService"/>
    </application>


</manifest> 


 

 

MyService.java文件內容如下:

package com.demo.myMusicPlayer;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service{
	MediaPlayer mp;
	ServiceReceiver serviceReceiver;
	//當前狀態,1沒有聲音播放,2正在播放音樂,3暫停
	int status = 1;
	@Override
	public IBinder onBind(Intent arg0) {

		// TODO Auto-generated method stub
		return null;
	}
	
	//當服務第一次創建時調用該方法
	public void onCreate(){
		status = 1;
		//創建BroadcastReceiver
		serviceReceiver = new ServiceReceiver();
		//創建IntentFilter過濾器
		IntentFilter filter = new IntentFilter();
		//添加Action
		filter.addAction("com.demo.myMusicPlayer.control");
		//註冊監聽
		registerReceiver(serviceReceiver,filter);
		super.onCreate();
	}
	
	//當服務銷燬時調用該方法
	public void onDestroy(){
		//取消註冊
		unregisterReceiver(serviceReceiver);
		super.onDestroy();
	}
	
	public class ServiceReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		//得到解決Intent中的數據
		int action = intent.getIntExtra("ACTION",-1);
		switch(action){
		case 1:
			if(status == 1)
			{
				//播放或者暫停聲音
				mp = MediaPlayer.create(context, R.raw.tianmimi);
				status = 2;
				Intent sendIntent = new Intent("com.demo.myMusicPlayer.update");
				sendIntent.putExtra("update", 2);
				sendBroadcast(sendIntent);
				mp.start();
			}
			else if(status == 2)
			{
				//正在播放聲音,停止、改變狀態
				mp.pause();
				status = 3;
				Intent sendIntent = new Intent("com.demo.myMusicPlayer.update");
				//存放數據
				sendIntent.putExtra("update", 3);
				//發送廣播
				sendBroadcast(sendIntent);
			}
			else if(status == 3)
			{
				//暫停中要播放聲音,改變狀態
				mp.start();
				status = 2;
				Intent sendIntent = new Intent("com.demo.myMusicPlayer.update");
				sendIntent.putExtra("update", 2);
				sendBroadcast(sendIntent);
			}
			break;
			
		case 2:
			//停止聲音
			if(status ==2 || status ==3)
			{
				//停止播放,改變狀態
				mp.stop();
				status = 1; 
				Intent sendIntent = new Intent("com.demo.myMusicPlayer.update");
				//存放數據
				sendIntent.putExtra("update", 1);
				//發送廣播
				sendBroadcast(sendIntent);
			}
			break;
		}
	}
	
}
	
	
}


 

 

myMusicPlayer.java文件內容如下:

package com.demo.myMusicPlayer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class myMusicPlayer extends Activity {
	
	//播放、暫停按鈕
	ImageButton start;
	//停止按鈕
	ImageButton stop;
	ActivityReceiver activityReceiver;
	//當前狀態,1沒有聲音播放,2正在播放音樂,3暫停
	int status = 1;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //元素綁定
        start = (ImageButton)this.findViewById(R.id.startplay);
        stop = (ImageButton)this.findViewById(R.id.stopplay);
        
        //創建Intent
        final Intent intent = new Intent("com.demo.myMusicPlayer.control");
        
        //爲按鈕添加監聽
        start.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//存放數據
				intent.putExtra("ACTION", 1);
				//發送廣播
				sendBroadcast(intent);
			}
        });
        
        //爲按鈕添加監聽
        stop.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//存放數據
				intent.putExtra("ACTION", 2);
				//發送廣播
				sendBroadcast(intent);
			}
        });
        
        //創建BroadcastReceiver
        activityReceiver = new ActivityReceiver();
        //創建IntentFilter過濾器
        IntentFilter filter = new IntentFilter();
        //添加Action
        filter.addAction("com.demo.myMusicPlayer.update");
        //註冊監聽
        registerReceiver(activityReceiver,filter);
        //創建Intent
        Intent i = new Intent(this,MyService.class);
        //啓動後臺Service
        startService(i);
        
    }
    
    public class ActivityReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			//得到解決Intent中的數據
			int update = intent.getIntExtra("update", -1);
			switch(update){
			case 1:
				//沒有聲音播放,設置當前狀態
				status = 1;
				break;
			case 2:
				//正在播放聲音,更換圖片
				start.setImageResource(R.drawable.play2);
				status = 2;
				break;
			case 3:
				//暫停中,更換當前圖片
				start.setImageResource(R.drawable.play1);
				status = 3;
				break;
			}
			
		}
    	
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		//彈出菜單
		menu.add(0,Menu.FIRST,0,"退出")
		.setIcon(android.R.drawable.ic_menu_delete);
		return true;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//創建Intent
		Intent intent = new Intent(this,MyService.class);
		//停止後臺Service
		stopService(intent);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()){
		case Menu.FIRST:
			//顯示對話框
			new AlertDialog.Builder(this)
			.setTitle("你確定退出嗎?")
			.setPositiveButton("確定", new android.content.DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					//直接退出
					System.exit(0);
				}
			})
			.setNegativeButton("取消", null)
			.create().show();
			break;
		}
		return false;
	}
    
    
}

 

1)初始化時候(未播放音樂)的界面

 

2)播放音樂的界面。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章