一个永不停止的简单服务。为什么?

时间:2017-02-02 20:14:39

标签: android android-service

我正在开发一个非常简单的应用程序,永远播放一首歌,直到用户停止它。 我使用bind / unbind服务函数只是为了从活动向服务发送一个简单的消息(hello)。

问题在于,当我点击停止播放歌曲时,它不会停止(即使在Logcat中我看到"停止"字符串)。为什么?

这是我的代码:

MainActivity:

public class MainActivity extends AppCompatActivity {

    boolean started = false;
    boolean musicBound = false;
    TextView button;

    private Intent playIntent;
    private PlayerService musicSrv;

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

        button = (TextView) findViewById(R.id.playstopbutton);

        playIntent = new Intent(this, PlayerService.class);

    }

    @Override
    public void onResume(){
        super.onResume();
        // put your code here...
        if(!started) {
          //  button.setText(">");
        }else{
          //  button.setText("||");
        }

    }

    //connect to the service
    private ServiceConnection musicConnection = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("My App", "conn");
            PlayerService.MusicBinder binder = (PlayerService.MusicBinder)service;
            //get service
            musicSrv = binder.getService();
            //pass list
            musicSrv.tryit("hello");
            musicBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("My App", "disc");
            musicBound = false;
        }
    };

    public void playstop(View v)
    {
        if(!started) {
            Log.i("My App", "start");
            started = true;
          //  button.setText("||");
            bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
            startService(playIntent);
        }else{
            Log.i("My App", "stop");
            started = false;
          //  button.setText(">");
            stopService(playIntent);
            musicSrv=null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {

        if (musicConnection != null) {
            unbindService(musicConnection);
        }

        stopService(playIntent);
        musicSrv=null;
        super.onDestroy();
    }

}

PlayerService:

public class PlayerService extends Service
{
    MediaPlayer mediaPlayer = null;
    String title = "aaaa";
    String msg = "bbbb";
    String ticker = "just a ticker";

    private final IBinder musicBind = new MusicBinder();

    @Override
    public void onCreate() {
        mediaPlayer = MediaPlayer.create(this, R.raw.song);
    }

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

        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.setLooping(true);
            mediaPlayer.start();
        }

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        Notification notification = new Notification.Builder(this)
                .setContentTitle(title)
                .setContentText(msg)
                .setSmallIcon(R.drawable.note2)
                .setContentIntent(pendingIntent)
                .setTicker(ticker).setColor(0xff222222).build();



        startForeground(11, notification);

        return START_STICKY;
    }

    //binder
    public class MusicBinder extends Binder {
        PlayerService getService() {
            return PlayerService.this;
        }
    }

    //activity will bind to service
    @Override
    public IBinder onBind(Intent intent) {
        return musicBind;
    }

    //release resources when unbind
    @Override
    public boolean onUnbind(Intent intent){
        mediaPlayer.stop();
        mediaPlayer.release();
        return false;
    }

    public void tryit(String stringa){
       Log.i("My App", stringa);

    }

    public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
        stopForeground(true);
        Log.i("PROVA SERVICE", "Distruzione Service");
    }

}

1 个答案:

答案 0 :(得分:2)

  

当我点击停止播放歌曲时,它不会停止

因为您只在stop()上调用MediaPlayer,如果:

  • 客户端解除绑定(onUnbind()),这不是您的客户正在做的事情,或者

  • 客户端取消绑定停止它(onDestroy()),这不是您的客户正在做的事情

当以下两个陈述都成立时,服务将被销毁:

  • 每个绑定的客户都是解除绑定,
  • 如果已为此服务调用startService(),则会调用stopService()

在这种情况下,您正在调用stopService(),但您仍然使用该服务,因此不会调用onDestroy()