实施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