Android making thread in service

2019-09-09 15:32发布

I'm making MediaPlayer service and I don't want to use application resource for service. I read that I must create new thread in service,but I'm beginner and I can't understand how to do this. I know how to start new thread but I don't know how to process startPlay and stopAll method in thread

package com.filsoft.mouse;

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

public class Sound extends Service implements OnCompletionListener {
      MediaPlayer[] mediaPlayer=new MediaPlayer[3];
      private final IBinder mBinder = new LocalBinder();

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

      @Override
      public void onCreate() {
        mediaPlayer[0] = MediaPlayer.create(this, R.raw.sound1);
        mediaPlayer[0].setOnCompletionListener(this);
        mediaPlayer[0].setLooping(true);

        mediaPlayer[1] = MediaPlayer.create(this, R.raw.sound2);           
mediaPlayer[1].setOnCompletionListener(this);
        mediaPlayer[1].setLooping(true);

        mediaPlayer[2] = MediaPlayer.create(this, R.raw.sound3);
        mediaPlayer[2].setOnCompletionListener(this);
        mediaPlayer[2].setLooping(true);
        }
      public void startPlay(int idx)
      {
          stopAll();
          if (!mediaPlayer[idx].isPlaying()) {
              mediaPlayer[idx].start();
            }
      }
      public class LocalBinder extends Binder {
            public Sound getService() {
                return Sound.this;
            }

        }
      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {

        return START_STICKY;
      }
      public void stopAll()
      {
           if (mediaPlayer[0].isPlaying()) {
                  mediaPlayer[0].stop();
                }
                if (mediaPlayer[1].isPlaying()) {
                      mediaPlayer[1].stop();
                }
                if (mediaPlayer[2].isPlaying()) {
                      mediaPlayer[2].stop();
                }
      }

      public void onDestroy() {
        stopAll();
        mediaPlayer[0].release();
        mediaPlayer[1].release();
        mediaPlayer[2].release();

      }

      public void onCompletion(MediaPlayer _mediaPlayer) {
        stopSelf();
      }

    }

0条回答
登录 后发表回答