實施account authenticators有三條腿的授權流程,當我最近一直在思考這個問題。將結果發送回服務進行處理比在活動中處理結果要好。它還提供了更好的問題分離。
它不是那麼明確記載,但Android提供了一個簡單的方法來與ResultReceiver
任何地方發送和接收結果(包括服務)。
我發現它比傳遞活動要乾淨得多,因爲這總會帶來泄漏這些活動的風險。另外,調用具體的方法不夠靈活。
要在服務中使用ResultReceiver
,你需要繼承它,並提供一種方法來處理接收到的結果,通常是在一個內部類:
public class SomeService extends Service {
/**
* Code for a successful result, mirrors {@link Activity.RESULT_OK}.
*/
public static final int RESULT_OK = -1;
/**
* Key used in the intent extras for the result receiver.
*/
public static final String KEY_RECEIVER = "KEY_RECEIVER";
/**
* Key used in the result bundle for the message.
*/
public static final String KEY_MESSAGE = "KEY_MESSAGE";
// ...
/**
* Used by an activity to send a result back to our service.
*/
class MessageReceiver extends ResultReceiver {
public MessageReceiver() {
// Pass in a handler or null if you don't care about the thread
// on which your code is executed.
super(null);
}
/**
* Called when there's a result available.
*/
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Define and handle your own result codes
if (resultCode != RESULT_OK) {
return;
}
// Let's assume that a successful result includes a message.
String message = resultData.getString(KEY_MESSAGE);
// Now you can do something with it.
}
}
}
當你在服務啓動的活動,創建一個結果接收機,它包入意圖演員:
/**
* Starts an activity for retrieving a message.
*/
private void startMessageActivity() {
Intent intent = new Intent(this, MessageActivity.class);
// Pack the parcelable receiver into the intent extras so the
// activity can access it.
intent.putExtra(KEY_RECEIVER, new MessageReceiver());
startActivity(intent);
}
最後,在活動中,解包接收器,並使用ResultReceiver#send(int, Bundle)
一個結果送回去。
您可以隨時發送結果,但在這裏我選擇了做整理之前:
public class MessageActivity extends Activity {
// ...
@Override
public void finish() {
// Unpack the receiver.
ResultReceiver receiver =
getIntent().getParcelableExtra(SomeService.KEY_RECEIVER);
Bundle resultData = new Bundle();
resultData.putString(SomeService.KEY_MESSAGE, "Hello world!");
receiver.send(SomeService.RESULT_OK, resultData);
super.finish();
}
}
它可以用一個簡單的黑客來實現,通過使用SharedPreferences的,[SO]( http://stackoverflow.com/a/31461941/4859873) – 2015-07-16 18:46:48