后台播放music示例

来源:互联网 发布:科比职业生涯数据 编辑:程序博客网 时间:2024/05/16 14:35

也是从别人那里搬来学习的。


MusicDemo.java

package com.example.and_musicdemo0826;import android.os.Bundle;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.view.Menu;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;  @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);         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);       }   @Overridepublic void onClick(View v) {// TODO Auto-generated method stubif(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);           }                  }   }

MusicService.java

package com.example.and_musicdemo0826;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.util.Log;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.example.and_musicdemo0826.PLAY_ACTION";       public static final String PAUSE_ACTION = "com.example.and_musicdemo0826.PAUSE_ACTION";       public static final String NEXT_ACTION = "com.example.and_musicdemo0826.NEXT_ACTION";       public static final String PREVIOUS_ACTION = "com.example.and_musicdemo0826.PREVIOUS_ACTION";private static final String TAG = "MusicService"; @Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();mMediaPlayer = new MediaPlayer();           //通过一个URI可以获取所有音频文件           Uri MUSIC_URL = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;           //这里我过滤了一下,因为我机里有些音频文件是游戏音频,很短           //播放不到一秒钟,我这里作了处理,默认大于10秒的可以看作是歌         if(mCursor==null || mCursor.getCount()==0){        mCursor = getContentResolver().query(MUSIC_URL, mCursorCols, MediaStore.Audio.Media.DURATION + "> 10000", null, null);           }        }@Overridepublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubsuper.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);           Log.i(TAG,"dataColumn " + dataColumn + " data " + data);        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);           Log.i(TAG,"titleColumn " + titleColumn + " artistColumn " + artistColumn + "->info " + info);        return info;                  }     //服务结束时要释放MediaPlayer       public void onDestroy() {           super.onDestroy();           mMediaPlayer.release();       }   }

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.and_musicdemo0826"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="10"        android:targetSdkVersion="16" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.and_musicdemo0826.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></manifest>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" />    <RelativeLayout        android:id="@+id/relativeLayout1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:layout_alignParentLeft="true"        android:layout_alignParentRight="true"        android:layout_marginBottom="161dp"        android:layout_marginLeft="8dp"        android:layout_marginRight="8dp"        android:orientation="vertical" >        <Button            android:id="@+id/play"            android:layout_width="70dp"            android:layout_height="wrap_content"            android:text="@string/play" />         <Button        android:id="@+id/previous"        android:layout_width="78dp"        android:layout_height="wrap_content"  android:layout_toRightOf="@id/play"        android:text="@string/previous" />        <Button            android:id="@+id/next"            android:layout_width="78dp"            android:layout_height="wrap_content"            android:layout_toRightOf="@id/previous"            android:text="@string/next" />        <Button            android:id="@+id/pause"            android:layout_width="70dp"            android:layout_height="wrap_content"            android:layout_toRightOf="@id/next"            android:text="@string/pause" />    </RelativeLayout>   </RelativeLayout>


原创粉丝点击