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)播放音乐的界面。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值