public class Foo extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = new Intent(this, SampleIntentService.class);
i.putExtra("receiver", mReceiver);
startService(i);
}
@Override
public void onDestroy() {
stopService(new Intent(this, SampleIntentService.class));
mReceiver = null;
super.onDestroy();
}
ResultReceiver mReceiver = new ResultReceiver(new Handler()) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Handle response from IntentService here
}
};
}
这是一个示例 IntentService
public class SampleIntentService extends IntentService {
public SampleIntentService() {
super(SampleIntentService.class.getName());
}
@Override
protected void onHandleIntent(Intent intent) {
ResultReceiver rec = intent.getParcelableExtra("receiver");
if (rec != null) {
rec.send(200, null);
}
}
}