在service中播放音乐

MainActivity:

public class MainActivity extends Activity {
    private MyReceiver receiver;
    private Button btnStartOrPause;
    private String receiverAction = "com.pepelu.musicplayer";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // 动态注册广播,不需要再在Manifest中注册
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter(receiverAction);
        registerReceiver(receiver, filter);
        // button
        btnStartOrPause = (Button) findViewById(R.id.button1);
    }

    public void clickHandle(View view) {
        int id = view.getId();
        if (id == R.id.button1) {//播放,暂停
            Intent intent = new Intent(this, MusicPlayerService.class);
            Bundle bundle = new Bundle();
            File file = new File(Environment.getExternalStorageDirectory(), "残酷天使.mp3");
            bundle.putString("audioPath", file.getPath());
            bundle.putString("receiverAction", receiverAction);
            intent.putExtras(bundle);
            startService(intent);
        } else if (id == R.id.button2) {//停止
            Intent intent = new Intent(this, MusicPlayerService.class);
            stopService(intent);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解除注册
        unregisterReceiver(receiver);
    }

    public class MyReceiver extends BroadcastReceiver {
        /**
         * 更新UI
         */
        @Override
        public void onReceive(Context context, Intent intent) {
//            String name = intent.getStringExtra("name");
//            Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
//            btnStartOrPause.setText("暂停");
            int backFlag=intent.getIntExtra("backFlag", 0);
            switch (backFlag) {
            case 0:
                btnStartOrPause.setText("暂停");
                break;
            case 1:
            case 2:
            case 3:
                btnStartOrPause.setText("播放");
                break;
            default:
                break;
            }
        }

    }
}

Service:

public class MusicPlayerService extends Service {
    private MediaPlayer player;
    private Intent mIntent;
    private Bundle bundle;
    private String audioPath;
    private String receiverAction;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // super.onStartCommand(intent, flags, startId);
        if (mIntent == null) {
            mIntent = intent;
        }
        audioPath = mIntent.getExtras().getString("audioPath");
        receiverAction = mIntent.getExtras().getString("receiverAction");
        // 正在播放
        if (player != null && player.isPlaying()) {
            player.pause();
            sendBC4UpdateUI(1);
        } else {
            // 第一次播放
            if (player == null) {
                player = new MediaPlayer();
                try {
                    player.setDataSource(audioPath);
                    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    player.prepare();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 异步缓冲
            // player.prepareAsync();
            // player.setOnPreparedListener(new OnPreparedListener() {
            // @Override
            // public void onPrepared(MediaPlayer mp) {
            // player.start();
            // }
            // });
            //开始播放
            player.start();
            sendBC4UpdateUI(0);
            //一曲播放结束
            player.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    //播放器重置
                    player.reset();
                    player = null;
                    sendBC4UpdateUI(3);
                }
            });
        }
        return START_STICKY;

    }

    @Override
    public void onDestroy() {
        // 释放掉player资源
        if (player != null) {
            player.release();
            sendBC4UpdateUI(2);
        }
        super.onDestroy();
    }

    /**
     * 更新界面
     * 
     * @param flag
     */
    private void sendBC4UpdateUI(int flag) {
        Intent intent = new Intent(receiverAction);
        // 如果缺少下面这句,关掉再重新打开播放器里点“停止”并不能停掉
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        bundle = new Bundle();
        bundle.putInt("backFlag", flag);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }
}

布局文件:

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.pepelu.musicplayer.MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="clickHandle"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp"
        android:text="播放" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="clickHandle"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_marginLeft="52dp"
        android:layout_toRightOf="@+id/button1"
        android:text="停止" />

</RelativeLayout>
View Code

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pepelu.musicplayer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            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="com.pepelu.musicplayer.service.MusicPlayerService" >
        </service>

       
    </application>

</manifest>
View Code

参考博客:

简易mp3播放器 :http://blog.csdn.net/ouyang_peng/article/details/8777709

使用service播放MP3:http://www.cnblogs.com/giuz/archive/2010/10/31/1865470.html

service的使用:http://segmentfault.com/a/1190000000507084

原文地址:https://www.cnblogs.com/mada0/p/4862147.html