使用意图来控制另一个活动

时间:2014-06-15 08:13:35

标签: android android-intent android-activity

我有2项活动:MainActivity和PlayActivity。在MainActivity中,我正在播放一首歌,在PlayActivity中,我正在播放该歌曲的图像和停止按钮。播放PlayActivity时如何停止播放MainActivity中的歌曲?你们能举个例子吗? enter image description here

1 个答案:

答案 0 :(得分:1)

就个人而言,我宁愿让服务播放这首歌。然后,PlayActivity可以仅显示该服务的当前歌曲,然后播放和停止歌曲将向该服务发送消息以播放或停止该歌曲。 MainActivity将让服务知道要播放的歌曲,然后播放活动将能够显示当前正在播放的歌曲,并且能够控制它,而无需来回发送一些精细的消息。

public class MusicApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Context context = getApplicationContext();
        context.startService(new Intent(context, MusicService.class));
    }
}

public interface MusicControlInterface {
    public void startMusic(Track track);
    public void stopMusic();
    ...
    forward, rewind, whatever controls you need
    ...
}

public class MusicService extends Service implements MusicControlInterface {
    private final IBinder binder = new LocalBinder();

    public IBinder inBind(Intent intent) {
        return binder;
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    ...
    whatever methods you more need, onCreate, etc.
    ...

    //implementation of the MusicControlInterface
    public void playMusic(Track track) {
        //start playing the track using whatever means you use to pay the tracks
    }

    public void stopMusic() {
        //Stop the music using whatever method you play with.
    }

    public class LocalBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }
}

然后,活动就会像这样绑定到服务。

public class MainActivity {
    private MusicService musicService;

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName name, IBinder service) {
            MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
            musicService = binder.getService();
        }

        public void onServiceDisconnected(ComponentName name) {
            musicService = null;
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(this, MusicService.class);
        this.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    public void playButtonClick() {
        if (musicService != null) musicService.playMusic(...sometrack...);
    }
}

然后,每当您需要拨打该服务时,您只需致电     if(musicService!= null)musicService.stopMusic();

检查null是个好主意,因为服务绑定可能需要一段时间。