android – 一旦活动结束,就会调用onStartCommand服务

当我点击播放按钮播放歌曲并将歌曲mp3与它捆绑在一起并在onStartCommand中接收时,我开始服务.问题是当我启动服务的活动结束时,我的服务再次调用onStartCommand.当它接收该捆绑时它不存在,因为这次活动没有启动它.因此,我在准备媒体播放器时遇到了非法的例外情况.我没有约束我的服务.

为什么在我的活动结束时会调用onStartCommand?

启动服务:

Intent i = new Intent(SongList.this,MyService.class);
i.putExtra("songURL",user.songurlz);
i.putExtra("songNAME",songplay_name);
startService(i);

服务类:

public class MyService extends Service {

    static MediaPlayer mediaPlayer;
    static int pauseplay;
    static notificationmanager notificationmanagerPlay;
    static CharSequence tickerText;
    static Notification notification4;//Notification variable(for song playing)
    TelephonyManager telephonyManager;
    PhonestateListener listener;
    static Notification notification;
    static notificationmanager mnotificationmanager;
    String songurl;
    String songname;

    @Override
    public IBinder onBind(Intent intent) {
        // Todo Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
        pauseplay = 1;
        MainMenu.serviceRunning = 1;
        telephonyManager = (TelephonyManager) getSystemService(
                Context.TELEPHONY_SERVICE);
        // Create a new PhonestateListener
        listener = new PhonestateListener() {

            @Override
            public void onCallStateChanged(int state,String incomingNumber) {
                switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    if (mediaPlayer.isPlaying() == true && mediaPlayer != null){
                        pauseSong();
                    }
                    break;
                }
            }
        };
        // Register the listener wit the telephony manager
        telephonyManager.listen(listener,PhonestateListener.LISTEN_CALL_STATE);
    }

    public int onStartCommand(Intent intent,int flags,int startId) {
        super.onStartCommand(intent,flags,startId);
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            //Retrieve your data using the name
            songurl = bundle.getString("songURL");
            Bundle bundle2 = intent.getExtras();
            //Retrieve your data using the name
            songname = bundle2.getString("songNAME");
        }
        Toast toast = Toast.makeText(getApplicationContext(),"Now Playing: "
                + songname,Toast.LENGTH_LONG);
        toast.show();
        // configure the intent
        Intent playIntent = new Intent(MyService.this,SongList.class);
        final PendingIntent pendingIntent = PendingIntent.getActivity(
                MyService.this,playIntent,0);
        notification = new Notification(R.drawable.playicon,"Buffering...",System.currentTimeMillis());
        notification.contentView = new RemoteViews(getPackageName(),R.layout.custom_notification2);
        notification.contentIntent = pendingIntent;
        if (SongList.bitmap != null) {
            notification.contentView.setimageViewBitmap(R.id.notifimage,SongList.bitmap);
        } else {
            notification.contentView.setimageViewResource(R.id.notifimage,R.drawable.icon);
        }
        notification.contentView
                .setTextViewText(R.id.notiftitle,"Now Playing");
        notification.contentView.setTextViewText(R.id.notiftext,songname);
        notification.flags = notification.flags
                | Notification.FLAG_ONGOING_EVENT;
        mnotificationmanager = (notificationmanager) getApplicationContext()
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mnotificationmanager.notify(4,notification);
        mediaPlayer.reset();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mediaPlayer.setDataSource(songurl);
        } catch (IllegalArgumentException e) {
            e.printstacktrace();
        } catch (IllegalStateException e) {
            e.printstacktrace();
        } catch (IOException e) {
            e.printstacktrace();
        }
        // register an error listener via MediaPlayer's setonErrorListener
        mediaPlayer.setonErrorListener(new OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp,int what,int extra) {
                Log.e("MEDIAPLAYER ERRORS","what: " + what + "  extra: "
                        + extra);
                mediaPlayer.reset();
                mnotificationmanager.cancel(4);
                return false;
            }
        });
        mediaPlayer.prepareAsync();
        mediaPlayer.setonPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                mediaPlayer.start();
            }
        });
        mediaPlayer
                .setonCompletionListener(new MediaPlayer.OnCompletionListener(){

                    public void onCompletion(MediaPlayer mp) {
                        stopSelf();
                    }
                });
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        MainMenu.serviceRunning = 0;
        mnotificationmanager.cancel(4);
    }

    public static void pauseSong() {
        if (mediaPlayer.isPlaying() == true) {
            mediaPlayer.pause();
            mnotificationmanager.cancel(4);
            pauseplay = 0;
        }
    }

    public static void playSong() {
        if (pauseplay == 0) {
            mnotificationmanager.notify(4,notification);
            mediaPlayer.start();
            pauseplay = 1;
        }
    }
}

解决方法

Why does the onStartCommand get called when my activity ends?

要么在“活动结束”时调用startService()(无论这意味着什么),要么Android因为您使用START_STICKY而因某种原因重新启动服务.

就个人而言,对于音乐播放器,我认为START_NOT_STICKY是正确的答案.如果您的服务因任何原因而停止,用户应该负责再次启动它.

相关文章

这篇“android轻量级无侵入式管理数据库自动升级组件怎么实现...
今天小编给大家分享一下Android实现自定义圆形进度条的常用方...
这篇文章主要讲解了“Android如何解决字符对齐问题”,文中的...
这篇文章主要介绍“Android岛屿数量算法怎么使用”的相关知识...
本篇内容主要讲解“Android如何开发MQTT协议的模型及通信”,...
本文小编为大家详细介绍“Android数据压缩的方法是什么”,内...