安卓Service和Broadcast实现简单的音乐播放器

做实验的时候使用Service和Broadcast实现了一个功能较为简单的音乐播放器,可以对音乐进行播放、暂停和停止。
主要思路:
1、使用Service在后台播放音乐
2、Broadcast发送广播通知Activity更改界面
程序运行界面:

实现代码:

1、布局界面XML如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/musicbar"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:navigationIcon="@drawable/logo"
        app:titleTextColor="@color/white" />

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="100dp" />

    <ImageView
        android:id="@+id/photo"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_gravity="center"
        android:layout_marginBottom="20dp"
        app:srcCompat="@drawable/qielogo" />

    <TextView
        android:id="@+id/musictext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="100dp"
        android:text="暂无播放音乐"
        android:textSize="28dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/start"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_weight="1"
            android:background="@color/white"
            android:scaleType="centerInside"
            app:srcCompat="@drawable/start" />

        <ImageButton
            android:id="@+id/stop"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_weight="1"
            android:background="@color/white"
            android:scaleType="centerInside"
            app:srcCompat="@drawable/stop" />

    </LinearLayout>
</LinearLayout>

2、主Acitivy如下

package com.example.test6;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toolbar;

public class Music extends AppCompatActivity {
    TextView musictext;
    Toolbar musicbar;
    ImageView photo;
    ImageButton startbutton;
    Integer state = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);

        IntentFilter inf = new IntentFilter();
        inf.addAction("com.user.action");
        registerReceiver(broad,inf);

        musictext = findViewById(R.id.musictext);
        photo = findViewById(R.id.photo);
        //musicbar = findViewById(R.id.musicbar);
        startbutton = findViewById(R.id.start);
        ImageButton stopbutton = findViewById(R.id.stop);

        startbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (state){
                    case 1:
                        state = 2;
                        break;
                    default:
                        state = 1;
                        break;
                }
                Log.v("当前状态","1");
                Intent intent = new Intent(Music.this,MusicService.class);
                intent.putExtra("action",state);
                startService(intent);
                Log.v("intent传值","1");
            }
        });

        stopbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Music.this,MusicService.class);
                stopService(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broad);
    }

    public BroadcastReceiver broad = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int i = intent.getIntExtra("action",-1);
            switch(i){
                case 1:
                    musictext.setText("China-X");
                    photo.setImageResource(R.drawable.yjtp);
                    startbutton.setImageResource(R.drawable.pause);
                    break;
                case 2:
                    startbutton.setImageResource(R.drawable.start);
                    musictext.setText("音乐暂停");
                    break;
                case 3:
                    state = 3;
                    musictext.setText("暂无播放音乐");
                    photo.setImageResource(R.drawable.qielogo);
                    startbutton.setImageResource(R.drawable.start);
                    break;
            }
        }
    };
}

3、Service类如下

package com.example.test6;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

public class MusicService extends Service {

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

    private MediaPlayer mp;

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

    }

    public void onStart(Intent intent,int startId){
        super.onStart(intent,startId);
        int i = intent.getIntExtra("action",0);
        if(i==1){
            if(null==mp) {
                mp = MediaPlayer.create(this, R.raw.mymusic);
                mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        stopSelf();
                    }
                });
            }
            mp.start();
        }else if(i==2){
            if(mp!=null&&mp.isPlaying()){
                mp.pause();
            }
        }
        Log.v("zhuangtai",String.valueOf(i));
        Intent in = new Intent("com.user.action");
        in.putExtra("action",i);
        sendBroadcast(in);
    }

    public void onDestroy(){
        super.onDestroy();
        mp.stop();
        Intent in = new Intent("com.user.action");
        in.putExtra("action",3);
        sendBroadcast(in);
    }
}
原文地址:https://www.cnblogs.com/does/p/13060289.html