微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

图1 播放界面

图2 暂停界面

图3 停止界面
实现代码

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;

public class Music extends AppCompatActivity {
    TextView musictext;
    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);
        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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐