search

Home  >  Q&A  >  body text

mediaplayer - android service 静态变量

音乐播放app,在播放service中有一个mediaplayer 静态变量,service启动后,我想从其他activity中取得这个变量,却发现总是null,难道一个service启动过后,他里面的数据都销毁了?

mediaplayer是在service的oncreate中初始化的

其实我是遇到这样的问题:音乐播放app,歌曲列表页面点击一首歌,到播放页面,通过intent传递点击的歌曲信息,同时启动播放service来播放。现在我想在外面的activity加一个正在播放按钮,点击后直接到播放页面,这个时候就没有携带歌曲信息,因此,想着在播放页面的oncreate中做个判断,如果携带了歌曲信息,启动service播放,没有,则只是打开页面,不播放,或继续播放正在播放的歌曲。
我的判断依据就是看service中的mediaplayer是不是null,现在问题就是不管有没有在播放,取到的值都是null

迷茫迷茫2772 days ago628

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-17 18:01:26

    At any time, it is not recommended to use global variables to transfer values ​​between any components (referring to the four major components), because: the IPC mechanism does not allow you to do this!

    I guess why you can't get the value may be related to the fact that you are using Remote Service. --- Local Service and the main program are in the same process. There is no problem in getting the value like you did, but Remote Service is across processes. No matter how you set the value, it will be null.

    The correct approach is: bind to the Service, then get the ServiceConnection, and use the ServiceConnection to operate or get the desired value.

    Please refer to:
    Android Develop > API Guides > Binding Service
    The difference between Android Local Service & Remote Service

    p.s. You can refer to how the open source project on github is implemented

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 18:01:26

    Since it is a static variable, it is related to the class and has nothing to do with the object, that is, it has nothing to do with the life cycle of the Service.
    I suggest you take a look at the initialization process of MediaPlayer. Is it initialized when it is declared, or is it initialized during the life cycle of the Service.

    Supplementary content:

    1. It is recommended to post the code and take a look. The focus is on the code where MediaPlayer is initialized and set to null again.

    2. If MediaPlayer is a static variable, it is only related to the class. If it is null after initialization, it must be some piece of logic in your code that assigns it to null again.

    reply
    0
  • Cancelreply