Bin*_*aby 18 android android-service android-activity greenrobot-eventbus
关于服务通信,我可以将EventBus库用作活动吗?
我在我的应用程序中尝试了以下内容:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
setContentView(R.layout.activity_music_player);
Intent serviceIntent=new Intent(MusicPlayerActivityTest.this,MusicPlayerServiceTest.class);
startService(serviceIntent);
EventBus.getDefault().post(new SetSongList(songArraList, 0));
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
Run Code Online (Sandbox Code Playgroud)
在我的服务中onEvent叫.
Ant*_*ony 26
您必须注册订阅者,而不是注册者.
因此,如果您希望获得该活动,请从您的应用中删除注册/取消注册.如果是这样,只需将onEvent(AnyEvent事件)方法添加到Application类.
然后在您的服务中注册EventBus onStart()并取消注册onStop().
它应该更好地工作.
在您的申请中
public class MyApp extend Application {
@Override
public void onCreate() {
super.onCreate();
...
EventBus.getDefault().post(new SetSongList(songArraList, 0));
}
}
Run Code Online (Sandbox Code Playgroud)
或在你的活动中
public class MyActivity extend Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
EventBus.getDefault().post(new SetSongList(songArraList, 0));
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的服务
public class MyService extends Service {
...
@Override
public void onCreate() {
super.onCreate();
EventBus.getDefault().register(this);
}
@Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
public void onEvent(SetSongList event){
// do something with event
}
...
}
Run Code Online (Sandbox Code Playgroud)
在我的情况下,zyamys 的评论有所帮助。此外,由于代码错误,安东尼的回答是正确的。
如果您使用不同的流程,答案是否定的。如果您使用不同的进程,则意味着它运行在不同的虚拟机上(如 Davlik)。所有静态字段都不同...!示例(AndroidManifest.xml):
<service android:name=".GPSTracker" android:process=":my_gps_tracker" />
Run Code Online (Sandbox Code Playgroud)
如果您在同一进程中运行服务,则答案为YES。示例(AndroidManifest.xml):
<service android:name=".GPSTracker"/>
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,我建议结合使用 Intents 和发送/接收广播功能在服务和活动之间发送数据。
| 归档时间: |
|
| 查看次数: |
10494 次 |
| 最近记录: |