如何在Fragment
/Activity
和Service
之間進行通信有多種技術。
其中之一是使用ResultReceiver並將其發送到IntentServiceIntent
額外。
您創建自定義接收器ServiceResultReceiver
延伸ResultReceiver
。
public class ServiceResultReceiver extends ResultReceiver {
private Receiver mReceiver;
public ServiceResultReceiver(Handler handler) {
super(handler);
}
public void setReceiver(Receiver receiver) {
mReceiver = receiver;
}
public interface Receiver {
public void onReceiveResult(int resultCode, Bundle resultData);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (mReceiver != null) {
mReceiver.onReceiveResult(resultCode, resultData);
}
}
}
使您的Fragment
實現ServiceResultReceiver.Receiver
接口。創建接收器 並將其初始化爲Fragment
。您比傳遞接收機服務和服務只是從意圖獲得接收機,並呼籲receiver.send()
發送任何回到接收機。
public class MyFragment extends ListFragment implements ServiceResultReceiver.Receiver {
private ServiceResultReceiver mReceiver;
....
@Override
public void onCreate(Bundle savedInstanceState) {
...
mReceiver = new ServiceResultReceiver(new Handler());
mReceiver.setReceiver(this);
}
public void startMyService() {
final Intent intent = new Intent(getActivity(), MyService.class);
intent.putExtra("receiver", mReceiver);
getActivity().startService(intent);
}
@Override
public void onReceiveResult(int resultCode, Bundle resultData) {
// service finished
}
}
public class MyService extends IntentService {
...
@Override
protected void onHandleIntent(Intent intent) {
// download data and update database
....
final ResultReceiver receiver = intent.getParcelableExtra("receiver");
if (receiver != null) {
receiver.send(0, null);
}
}
}
非常感謝你們,我會在今天晚些時候看看你們的解決方案,但他們都看起來很有前途 – 2012-07-25 08:10:06
我還沒有寫,但似乎你的第二個不足以滿足我的情況。但是'BrodcastReceiver'看起來正是我正在尋找的東西。非常感謝你! – 2012-07-25 17:40:59
LocalBroadcastManager對於這個特定的工作甚至更好:http://stackoverflow.com/questions/8802157/how-to-use-localbroadcastmanager。作品像一個魅力:) – 2012-07-25 18:37:21