android---(音乐播放、在服务中使用 mediaPlay)

android---(音乐播放、在服务中使用 mediaPlay)_第1张图片

android---(音乐播放、在服务中使用 mediaPlay)_第2张图片

android---(音乐播放、在服务中使用 mediaPlay)_第3张图片

android---(音乐播放、在服务中使用 mediaPlay)_第4张图片

android---(音乐播放、在服务中使用 mediaPlay)_第5张图片

android---(音乐播放、在服务中使用 mediaPlay)_第6张图片

android---(音乐播放、在服务中使用 mediaPlay)_第7张图片


public class MainActivity extends AppCompatActivity {

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


    public void playRes(View view) {

        MediaPlayer mp = MediaPlayer.create(this, R.raw.a1);
        mp.start();
    }


    public void playSys(View view) {

        MediaPlayer MP = new MediaPlayer();

        //skd 路径
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/a.mp3";
        try {
            MP.setDataSource(this, Uri.parse(path));
            //准备,相当于开始解析,同步执行
            MP.pause();
            MP.start();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public void playNet(View view) {

        MediaPlayer mp = new MediaPlayer();


        String uri = "http://sc1.111ttt.com/2015/1/11/01/104011137470.mp3";

        try {
            mp.setDataSource(this, Uri.parse(uri));

            //缓冲以后回调这个方法,才可以开始播放
            mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                   // mp.start();
                }
            });
            //异步缓冲
            mp.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
public class MainActivity extends AppCompatActivity implements
        View.OnClickListener, MediaPlayer.OnPreparedListener,
        MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {

    private Button play, pasume, per, nextplay;

    private MediaPlayer mp;

    //表示当前要播放音乐的索引
    private int index = 0;

    private ArrayList musiclist = new ArrayList<>();

    //判断播放 状态 true:暂停  false:播放
    private boolean isPause = false;

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

        initMusic();

        System.out.print(musiclist.size());
        mp = new MediaPlayer();

        mp.setOnPreparedListener(this);
        mp.setOnErrorListener(this);
    }


    /**
     * 初始化 组件
     */
    private void initView() {
        play = (Button) findViewById(R.id.player);
        pasume = (Button) findViewById(R.id.pasumeer);
        per = (Button) findViewById(R.id.per);
        nextplay = (Button) findViewById(R.id.nextplayer);

        play.setOnClickListener(this);
        pasume.setOnClickListener(this);
        per.setOnClickListener(this);
        nextplay.setOnClickListener(this);
    }

    /**
     * 音乐资源 初始化
     */
    private void initMusic() {
        String path =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getPath();

        musiclist.add(path + File.separator + "/sd.mp3");

        System.out.print(path + File.separator + "/sd.mp3");
        musiclist.add(path + File.separator + "/sd1.mp3");
    }


    /**
     * 按钮 单击 事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.player:
                play();
                break;
            case R.id.pasumeer:
                pause();

                break;
            case R.id.per:
                per();
                break;
            case R.id.nextplayer:
                next();

                break;
        }
    }

    /**
     * 上一首
     */
    private void per() {
        if (index - 1 > 0) {
            index--;
        } else {
            index = musiclist.size() - 1;
        }
        start();
    }

    /**
     * 下一首
     */
    private void next() {
        if (index + 1 < musiclist.size()) {
            index++;
        } else {
            index = 0;
        }
        start();
    }

    /**
     * 暂停
     */
    private void pause() {
        if (mp.isPlaying()) {
            mp.pause();
            isPause = true;
        }

    }

    /**
     * 播放
     */
    private void play() {
        if (isPause) {//如果是暂停,则直接播放
            mp.start();
            isPause = false;

        } else {//如果不是暂停,则要选回到空闲状态,再进行播放
            start();
        }

    }

    /**
     * 需要从头开始播放
     */
    private void start() {

        if (index < musiclist.size()) {

            if (mp.isPlaying()) {
                mp.stop();
            }

            String path = musiclist.get(index);
            //重置
            mp.reset();
            try {
                mp.setDataSource(path);
                mp.prepareAsync();//异步准备完毕,则开始播放
                isPause = false;
            } catch (IOException e) {
                e.printStackTrace();
            }


        }


    }

    /**
     * prepareAsync() 方法完成后,回调这个方法
     *
     * @param mp
     */
    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }

    /**
     * 出现 错误时
     *
     * @param mp
     * @param what
     * @param extra
     * @return
     */
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        mp.reset();
        return true;
    }

    /**
     * 音乐播放 完毕
     *
     * @param mp
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        next();//播放下一首
    }

    /**
     * activity 销毁时
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mp != null) {
            if (mp.isPlaying()) {
                mp.stop();
                mp.release();
            }
        }
    }
}

android---(音乐播放、在服务中使用 mediaPlay)_第8张图片

android---(音乐播放、在服务中使用 mediaPlay)_第9张图片

android---(音乐播放、在服务中使用 mediaPlay)_第10张图片

android---(音乐播放、在服务中使用 mediaPlay)_第11张图片

//音乐服务后台运行
public class MusicService extends Service implements
        MediaPlayer.OnPreparedListener {

    private MediaPlayer mediaPlayer;

    WifiManager.WifiLock lock = null;

    //事件类型
    public static final String ACTION_PLAY = "com.play.ACTION_PLAY";
    public static final String ACTION_PAUSE = "com.play.ACTION_PAUSE";
    public static final String ACTION_EXIT = "com.play.ACTION_EXIT";


    public MusicService() {
    }


    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();

        //后台保持 cpu 正常的工作
        mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        //后台保持 wifi 不被休眠
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        lock = wifiManager.createWifiLock("mylock");
        lock.acquire();

        mediaPlayer.setOnPreparedListener(this);


        //退出时,在通知栏显示
        notification();

    }

    private void notification() {

        Notification.Builder builder = new Notification.Builder(this);
        //提示的文字
        builder.setTicker("第一个音乐");

        //设置小图标
        builder.setSmallIcon(R.mipmap.ic_launcher);

        //标题
        builder.setContentTitle("我的音乐");

        PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, activity3.class),
                PendingIntent.FLAG_UPDATE_CURRENT);

        //设置 事件
        builder.setContentIntent(pi);

        //发送通知
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = builder.build();

        //作为前台的服务,退出时不会被系统给杀掉
        startForeground(0, notification);

        nm.notify(0, notification);
    }

    /**
     * 判断 不同的 action
     *
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String action = intent.getAction();

        if (ACTION_PLAY.equals(action)) {
            mediaPlayer.reset();
            try {
                mediaPlayer.setDataSource(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + File.separator + "sd.mp3");
                mediaPlayer.prepareAsync();

            } catch (IOException e) {
                e.printStackTrace();
            }


        } else if (ACTION_PAUSE.equals(action)) {

            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }

        } else if (ACTION_EXIT.equals(action)) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                mediaPlayer.release();
            }

        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @Override
    public void onPrepared(MediaPlayer mp) {
        mediaPlayer.start();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //释放锁 当暂停或停止时,要释放锁
        lock.release();

        stopForeground(true);//退出时,删除
    }
}
//点击按钮时运行 音乐后台服务
public class activity3 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity3);
    }


    public void play(View view) {
        Intent intent = new Intent(MusicService.ACTION_PLAY);
        startService(intent);
    }

    public void pasue(View view) {
        Intent intent = new Intent(MusicService.ACTION_PAUSE);
        startService(intent);
    }
}

//权限添加
//利用锁 保持后台服务继续运行
    "android.permission.INTERNET"/>
    "android.permission.WAKE_LOCK"/>

   ".MusicService"
            android:enabled="true"
            android:exported="true"
            android:process=":music"
            >
            
                "com.play.ACTION_PLAY"/>
                "com.play.ACTION_PAUSE"/>
                "com.play.ACTION_EXIT"/>
            
        

你可能感兴趣的:(Android)