我有服务和主要活动。有什么方法可以在这两者之间共享一个字符串。我在MainActivity中有一个方法,只有在服务的String到达之后才能执行。有没有办法做同样的事情。
感谢。
答案 0 :(得分:0)
以下代码将允许您的Service
向String
发布Activity
。如果您需要向另一个方向发送数据,请使用更为随意的方法,例如startService(Intent)
。
在BroadcastReceiver
中设置本地Activity
:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (!MyService.ACTION_NEW_STRING.equals(intent.getAction()) return;
String myString = intent.getStringExtra(MyService.EXTRA_STRING);
// do whatever you need to do here
}
}
@Override
public void onStart() {
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mReceiver, new IntentFilter(MyService.ACTION_NEW_STRING));
}
@Override
public void onStop() {
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(mReceiver);
}
在Service
声明需要的常量:
public static final String ACTION_NEW_STRING = "your_application_id.ACTION_NEW_STRING";
// or BuildConfig.APPLICATION_ID + ".ACTION_NEW_STRING" in Android Studio
public static final String EXTRA_STRING = "EXTRA_STRING";
private LocalBroadcastManager mManager;
@Override
public void onCreate() {
mManager = LocalBroadcastManager.getInstance(getApplicationContext());
}
在您拥有新的String
:
Intent i = new Intent(ACTION_NEW_STRING);
i.putExtra(EXTRA_STRING, myString);
mManager.sendBroadcast(i);
有关此主题的更多阅读:http://developer.android.com/reference/android/content/BroadcastReceiver.html