将服务从一项活动传递到另一项活动 [英] Pass Service From one Activity to Another

查看:96
本文介绍了将服务从一项活动传递到另一项活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将一项服务从一项活动传递到另一项活动?我有一个音乐播放器(Activity1),它显示歌曲列表,当您单击它时,它将在Activity1中启动服务.我有一个用户可以单击的按钮,它将打开Activity2.

how do I pass a service from one activity to another? I have a music player (Activity1) that displays a list of songs, and when you click on it, it starts the service within Activity1. I have a button that users can click that will open Activity2.

那么对我来说,将服务从Activity1传递到Activity2的最佳方法是什么?如果该服务在Activity1中启动,则Activity2应该继续播放.如果未在Activity1中启动该服务,则Activity2应该在使用它之前启动该服务.

So what is the best way for me to pass the service from Activity1 to Activity2. If the service is started in Activity1, then Activity2 should continue playing. If the service is not started in Activity1, then Activity2 should start the service before using it.

谢谢.

这里有一些示例代码,MusicService是扩展服务类的类.

Here's some sample code, the MusicService is a class that extends the service class.

 public class Activity1 extends AppCompatActivity {

 private MusicService serviceMusic;  

private ServiceConnection musicConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MusicService.PlayerBinder binder = (MusicService.PlayerBinder) service;
        //get service
        serviceMusic = binder.getService();
        serviceMusic.setSongList(songList);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
};

}

推荐答案

您可以定义Application扩展类,并在此类中使用public静态变量,并在所有活动中访问此变量.

you can define Application extend class and use public static variable in this class and access this variable in all activity .

像这样:

public class G extends Aplication{
   public static MusicService serviceMusic;  
}

和清单中:

  <application ...
    android:name=".G">

现在您可以在任何地方访问G.serviceMusic.

Now you can access G.serviceMusic any where.

这篇关于将服务从一项活动传递到另一项活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆