调用stopSelf()时服务不会停止

时间:2016-09-24 00:14:42

标签: android service broadcastreceiver android-service

我有一个应该在后台播放音乐的服务。我想要停止服务的通知,所以我创建了一个广播接收器,应该在通知点击时调用stopSelf(),但它似乎不起作用,我无法弄清楚原因。我的代码:

服务:

public class RadioService extends Service implements MediaPlayer.OnPreparedListener {

MediaPlayer radioPlayer;
String url = "radiourl";
String action;
NotificationManager notificationManager;
int NOTIFICATION_ID = 12345;


public RadioService() {
}

@Override
public IBinder onBind(Intent intent) {

    Log.e("Service", "Bind");

    return null;
}

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


    Log.e("Service", "onStart");
    action = intent.getAction();
    Log.e("ServiceAction", action);



    switch (action) {

        case "play":
        radioPlayer = new MediaPlayer();
        radioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        try {
            radioPlayer.setDataSource(url);
        } catch (IOException e) {
            Log.e("setDataSource", e.toString());
        }

        radioPlayer.prepareAsync();
        radioPlayer.setOnPreparedListener(this);

        case "stop":
            stopSelf();

    }



    return START_STICKY;

}

@Override
public void onPrepared(MediaPlayer radioPlayer) {

    Log.e("Service", "onPrepared");
    radioPlayer.start();

    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_play_arrow_black_24dp)
                    .setContentTitle("Radio")
                    .setContentText("Press to stop playback");



    registerReceiver(stopServiceReceiver, new IntentFilter("myFilter"));
    PendingIntent contentIntent = PendingIntent.getBroadcast(this, 0, new Intent("myFilter"), PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, builder.build());


}


@Override
public void onDestroy() {

    Log.e("Service", "onDestroy");

    if(notificationManager != null) {
        notificationManager.cancelAll();
    }

    //Zwolnij mediaplayer
    if(radioPlayer != null && radioPlayer.isPlaying()) {
        radioPlayer.stop();
        radioPlayer.reset();
        radioPlayer.release();
    }


    super.onDestroy();
}

protected BroadcastReceiver stopServiceReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        unregisterReceiver(stopServiceReceiver);
        stopSelf();
    }
};
}

0 个答案:

没有答案