你們好今天我將爲你們分享基於Service與ContentProvider的音樂播放實例,對於接觸Android有一些時日的人來講,Android的核心也就是Activity,Service,ContentProvider,BroadCastReceiver,以及串聯它們的Intent五大模塊,Activity我就不用多說了,而我將就這個例子來講一下Service,以及ContentProvider.java
Service:android
Android中的服務,它與Activity不一樣,它是不能與用戶交互的,運行在後臺的程序,若是咱們退出應用時,沒有結束進程,它仍然在後臺運行,那咱們何時會用到Service呢?好比咱們播放音樂的時候,有可能想邊聽音樂邊幹些其餘事情,當咱們退出播放音樂的應用,若是不用Service,咱們就聽不到歌了,因此這時候就得用到Service了,又好比當咱們一個應用的數據是經過網絡獲取的,不一樣時間(一段時間)的數據是不一樣的這時候咱們能夠用Service在後臺定時更新,而不用每打開應用的時候在去獲取。數據庫
CotentProvider:網絡
Android中的內容提供者,它讓咱們能夠經過一個URL跨應用獲取數據(一般是SQLite數據庫),我以爲Android這個仍是機制仍是很是不錯的,特別是咱們想獲取Sdcard裏一些數據時,好比咱們想獲取全部Sdcard裏的音頻,視頻,圖片等,咱們只要經過一個URL就能夠輕鬆搞定,其實咱們在開機或者插入Sdcard時,Android會作一些事情,就是它自動建庫,將咱們卡里全部音頻,視頻,圖片等信息存在相應的表中,咱們能夠用DDMS打開看一下以下圖(data/data目錄下),紅線是我手機當前卡創建的數據庫(不一樣卡會創建不一樣的數據庫)app
而後咱們能夠將這個數據庫導出,用能夠打開.db的工具打開瀏覽數據庫的相關信息以下圖所示(我這裏打開了音頻的數據表,能夠看到我手機裏全部音頻文件,固然還有數據表字段):ide
原本這個應用是我用來寫播放音樂Widget的代碼,可是佈局有點多,我就簡單化了,作了一個比較 簡單的Demo,老規矩Step by Step.工具
第一步:新建一個Android工程命名爲MusicDemo.佈局
第二步:候改main.xml佈局文件(我這裏增長了四個按鈕,上一首,播放,下一首,暫停)代碼以下:this
- <?xml version="1.0" encoding="utf-8"?>
- <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:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Welcome to Mr Wei's blog."
- />
- <LinearLayout
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- >
- <Button
- android:id="@+id/previous"
- android:layout_height="fill_parent"
- android:layout_width="wrap_content"
- android:layout_weight="1"
- android:text="上一首"
- />
- <Button
- android:id="@+id/play"
- android:layout_height="fill_parent"
- android:layout_width="wrap_content"
- android:layout_weight="1"
- android:text="播放"
- />
- <Button
- android:id="@+id/next"
- android:layout_height="fill_parent"
- android:layout_width="wrap_content"
- android:layout_weight="1"
- android:text="下一首"
- />
- <Button
- android:id="@+id/pause"
- android:layout_height="fill_parent"
- android:layout_width="wrap_content"
- android:layout_weight="1"
- android:text="暫停"
- />
- </LinearLayout>
- </LinearLayout>
第三步:新建一個MusicService.java類,播放音樂都是在這個類裏進行的哦,代碼以下:spa
- package com.tutor.music;
- import java.io.IOException;
- import android.app.Service;
- import android.content.Intent;
- import android.database.Cursor;
- import android.media.MediaPlayer;
- import android.net.Uri;
- import android.os.IBinder;
- import android.provider.MediaStore;
- import android.widget.Toast;
- public class MusicService extends Service {
- String[] mCursorCols = 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
- };
- private MediaPlayer mMediaPlayer;
- private Cursor mCursor;
- private int mPlayPosition = 0;
- public static final String PLAY_ACTION = "com.tutor.music.PLAY_ACTION";
- public static final String PAUSE_ACTION = "com.tutor.music.PAUSE_ACTION";
- public static final String NEXT_ACTION = "com.tutor.music.NEXT_ACTION";
- public static final String PREVIOUS_ACTION = "com.tutor.music.PREVIOUS_ACTION";
- @Override
- public IBinder onBind(Intent arg0) {
- // TODO Auto-generated method stub
- return null;
- }
- @Override
- public void onCreate() {
- super.onCreate();
- mMediaPlayer = new MediaPlayer();
- //經過一個URI能夠獲取全部音頻文件
- Uri MUSIC_URL = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
- //這裏我過濾了一下,由於我機裏有些音頻文件是遊戲音頻,很短
- //播放不到一秒鐘,我這裏做了處理,默認大於10秒的能夠看做是歌
- mCursor = getContentResolver().query(MUSIC_URL, mCursorCols, "duration > 10000", null, null);
- }
- @Override
- public void onStart(Intent intent, int startId) {
- super.onStart(intent, startId);
- 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();
- }
- }
- //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 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();
- }
- }
- //根據位置來獲取歌曲位置
- 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;
- }
- //服務結束時要釋放MediaPlayer
- public void onDestroy() {
- super.onDestroy();
- mMediaPlayer.release();
- }
- }
第四步:修改Musicdemo.java代碼以下(代碼比較簡潔易懂):
- package com.tutor.music;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class MusicDemo 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);
- //oncreate裏代碼一如既往的少
- setupViews();
- }
- //初始化一些工做
- public void setupViews(){
- component = new ComponentName(this,
- MusicService.class);
- mPrevious = (Button)findViewById(R.id.previous);
- mPlay = (Button)findViewById(R.id.play);
- mNext = (Button)findViewById(R.id.next);
- mPause = (Button)findViewById(R.id.pause);
- mPrevious.setOnClickListener(this);
- mPlay.setOnClickListener(this);
- mNext.setOnClickListener(this);
- mPause.setOnClickListener(this);
- }
- //按鈕點擊事件響應
- public void onClick(View v) {
- if(v == mPrevious){
- Intent mIntent = new Intent(MusicService.PREVIOUS_ACTION);
- mIntent.setComponent(component);
- startService(mIntent);
- }else if(v == mPlay){
- Intent mIntent = new Intent(MusicService.PLAY_ACTION);
- mIntent.setComponent(component);
- startService(mIntent);
- }else if(v == mNext){
- Intent mIntent = new Intent(MusicService.NEXT_ACTION);
- mIntent.setComponent(component);
- startService(mIntent);
- }else{
- Intent mIntent = new Intent(MusicService.PAUSE_ACTION);
- mIntent.setComponent(component);
- startService(mIntent);
- }
- }
- }
第五步:修改AndroidManifest.xml,這裏只是把咱們的MusicService申明進去,否則會報錯(第14行代碼),代碼以下:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.tutor.music"
- android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".MusicDemo"
- 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:name=".MusicService" android:exported="true" />
- </application>
- <uses-sdk android:minSdkVersion="7" />
- </manifest>