android之Service学习——音乐播放器

那个,网上关于Service的例子似乎大多都是音乐播放器哦,呵,俺也是参照着练习了一下害羞

 

 第一步:候改main.xml布局文件(我这里增加了四个按钮,上一首,播放,下一首,暂停)代码如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget38"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="暂停"
android:textSize="20sp"
android:textStyle="bold"
android:layout_alignTop="@+id/button3"
ndroid:layout_toRightOf="@+id/button3"
>
</Button>
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下一首"
android:textSize="20sp"
android:textStyle="bold"
android:layout_alignTop="@+id/button2"
android:layout_toRightOf="@+id/button2"
>
</Button>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放"
android:textSize="20sp"
android:textStyle="bold"
android:layout_alignTop="@+id/button1"
android:layout_toRightOf="@+id/button1"
>
</Button>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="上一首"
android:textSize="20sp"
android:textStyle="bold"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
>
</Button>
</RelativeLayout>

第二步:新建一个MyService.java类,播放音乐都是在这个类里进行,代码如下:

public class MyService extends Service 
{
	private MediaPlayer mMediaPlayer;
	private Cursor mCursor;
	private int mPlayPosition = 0;
	
	String[] projection = new String[] 
	{
			"audio._id AS _id", // index must match IDCOLIDX below
			MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
			MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
			MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ALBUM_ID,
			MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION
	};
	
	public static final String PLAY_ACTION = "com.csq.ServiceTest.PLAY_ACTION";
	public static final String PAUSE_ACTION = "com.csq.ServiceTest.PAUSE_ACTION";
	public static final String NEXT_ACTION = "com.csq.ServiceTest.NEXT_ACTION";
	public static final String PREVIOUS_ACTION = "com.csq.ServiceTest.PREVIOUS_ACTION";


	//创建时,系统调用
	public void onCreate() 
	{
		Log.i("Service", "onCreate");
		super.onCreate();
		mMediaPlayer = new MediaPlayer();
		//通过一个URI可以获取所有音频文件
		Uri MUSIC_URI = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
		//默认大于10秒的看作是歌
		mCursor = getContentResolver().query(MUSIC_URI, projection, "duration>10000", null, null);
	}
	
	//必须实现的一个方法,返回一个绑定的接口给Service
	//可以方法null,通常返回一个有AIDL定义的接口
	public IBinder onBind(Intent arg0) 
	{
		Log.i("Service", "onBind");
		return null;
	}

	//2.0以后用该方法替代onStart方法,在创建Service后也就是onCreate后调用,创建一次以后每次启动该服务都直接调用onStartCommand
	//如果只希望提供绑定,则不需要实现该方法
	public int onStartCommand(Intent intent, int flags, int startId) 
	{
		Log.i("Service", "onStartCommand");
		
		String action = intent.getAction();
		if(action.equals(PLAY_ACTION))
		{
			play();
		}else if(action.equals(PAUSE_ACTION))
		{
			pause();
		}else if(action.equals(NEXT_ACTION))
		{
			next();
		}else if(action.equals(PREVIOUS_ACTION))
		{
			previous();
		}
		
		return super.onStartCommand(intent, flags, startId);
	}

	//当Service不再启动时,系统调用
	public void onDestroy() 
	{
		Log.i("Service", "onDestroy");
		
		mMediaPlayer.release();
		
		super.onDestroy();
	}
	
	public void inite() 
	{
		mMediaPlayer.reset();
		String dataSource = getDateByPosition(mCursor, mPlayPosition);
		String info = getInfoByPosition(mCursor, mPlayPosition);
		//用Toast显示歌曲信息
		Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT).show();
		try {
			mMediaPlayer.setDataSource(dataSource);
			mMediaPlayer.prepare();
			mMediaPlayer.start();
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (IllegalStateException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	
	//play the music
	public void play() 
	{
		inite();
	}
	
	//暂停时,结束服务
	public void pause() 
	{
		stopSelf();
	}

	//上一首
	public void previous() 
	{
		if (mPlayPosition == 0) 
		{
			mPlayPosition = mCursor.getCount() - 1;
		} 
		else 
		{
			mPlayPosition--;
		}
		inite();
	}
	
	//下一首
	public void next() 
	{
		if (mPlayPosition == mCursor.getCount() - 1) 
		{
			mPlayPosition = 0;
		}
		else 
		{
			mPlayPosition++;
		}
		inite();
	}

	//根据位置来获取歌曲位置
	public String getDateByPosition(Cursor c,int position)
	{
		c.moveToPosition(position);
		int dataColumn = c.getColumnIndex(MediaStore.Audio.Media.DATA);
		String data = c.getString(dataColumn);
		return data;
	}
	//获取当前播放歌曲演唱者及歌名
	public String getInfoByPosition(Cursor c,int position)
	{
		c.moveToPosition(position);
		int titleColumn = c.getColumnIndex(MediaStore.Audio.Media.TITLE);
		int artistColumn = c.getColumnIndex(MediaStore.Audio.Media.ARTIST);
		String info = c.getString(artistColumn)+" " + c.getString(titleColumn);
		return info;
	}

}


 

第三步:修改MainActivity.java代码如下:

public class MainActivity extends Activity implements OnClickListener
{
	private Button mPrevious,mPlay,mNext,mPause;
	private ComponentName component;
	
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        component = new ComponentName(this,	MyService.class);
        
        mPrevious = (Button)findViewById(R.id.button1);
    	mPlay = (Button)findViewById(R.id.button2);
    	mNext = (Button)findViewById(R.id.button3);
    	mPause = (Button)findViewById(R.id.button4);

    	mPrevious.setOnClickListener(this);
    	mPlay.setOnClickListener(this);
    	mNext.setOnClickListener(this);
    	mPause.setOnClickListener(this);
    }

	public void onClick(View v) 
	{
		if(v == mPrevious)
		{
			Intent mIntent = new Intent(MyService.PREVIOUS_ACTION);
			mIntent.setComponent(component);
			startService(mIntent);
		}
		else if(v == mPlay)
		{
			Intent mIntent = new Intent(MyService.PLAY_ACTION);
			mIntent.setComponent(component);
			startService(mIntent);
		}
		else if(v == mNext)
		{
			Intent mIntent = new Intent(MyService.NEXT_ACTION);
			mIntent.setComponent(component);
			startService(mIntent);
		}
		else
		{
			Intent mIntent = new Intent(MyService.PAUSE_ACTION);
			mIntent.setComponent(component);
			startService(mIntent);
		}

	}
}


第四步:修改AndroidManifest.xml,这里只是把我们的MyService申明进去

<service android:name=".MyService"/>

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HelloAndroid

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值