Service 简介

Service是Android系统中的四大组件之一,它是一种长生命周期的,没有可视化界面,运行于后台的一种服务程序。

生命周期

在安卓的Service 中,有两种类型的srevice 一种是直接通过 startService 启动的servic 其生命周期不受 Activity 的限制,另一种Service 是和Activity 绑定的服务,其生命周期收到与之绑定的 upload successful

使用服务实现简单音乐播放器

权限声明


    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 允许写手机存储(必须) -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
    <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
    <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />

界面代码

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/paly"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="92dp"
        android:layout_marginTop="192dp"
        android:text="播放"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="192dp"
        android:layout_marginEnd="104dp"
        android:text="暂停"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="92dp"
        android:ems="10"
        android:inputType="text"
        android:text="音乐地址"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.457"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java


package cn.shilight.music;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Toast;

import java.io.File;


public class MainActivity extends AppCompatActivity {

    Button play,stop;
    EditText editText;

    private  MusicService.MyBinder myBinder;

    MyserviceConnection conn;

    Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        play = findViewById(R.id.paly);
        stop = findViewById(R.id.stop);
        editText = findViewById(R.id.address);
        conn = new MyserviceConnection();
        intent = new Intent(this, MusicService.class);
        bindService(intent,conn,BIND_AUTO_CREATE);


        play.setOnClickListener(view -> {

            String path = editText.getText().toString();




            if(path.length()!=0){

                File st = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
                    st = Environment.getStorageDirectory();
                    File pa = new File(st,"emulated/0/"+path);

                    Log.i("play", "onCreate: "+pa.getAbsolutePath());

                    if(pa.exists()&&pa.length()>0) {

                        myBinder.play(pa.getAbsolutePath());

                    }else{

                        Toast.makeText(MainActivity.this,"文件不存在",Toast.LENGTH_LONG).show();

                    }



                }


            }

        });



        stop.setOnClickListener(view -> {

            myBinder.stop();


        });











    }


    class MyserviceConnection implements ServiceConnection {


        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

            myBinder = (MusicService.MyBinder) iBinder;

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    }




}

MusicService.java


package cn.shilight.music;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import java.io.IOException;

public class MusicService extends Service {

    private MediaPlayer mediaPlayer;

    public  class MyBinder extends Binder{

        public void play(String path){


            try{
                if(mediaPlayer==null){
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mediaPlayer.setDataSource(path);
                    mediaPlayer.prepare();
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mediaPlayer) {
                            mediaPlayer.start();
                        }
                    });


                }




            }catch (IOException e){




            }



        }

        public void stop(){
            if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
                mediaPlayer.stop();
            }else if(mediaPlayer!=null&&!mediaPlayer.isPlaying()){
                mediaPlayer.start();
            }

        }


    }
    public MusicService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return new MyBinder();
    }
}