So i have a simple Question , it is Possible to Handle the Method onActivityResult() in a Service if this Activity was Started from the Same Service (Using Intent) ?
In
I recently stumbled upon the same issue, how to wire onActivityResult() outcome to a Service for an Activity started from the aforementioned Service. I did not want to store the Activity in a static variable given that Activity leak is a bad practice. So I added a static listener in the Activity handling onActivityResult() that implements an appropriate Interface and instantiated this listener as a private member of the Service class.
The code in a simplified form looks like this:
public class MyActivity extends FragmentActivity {
public Interface ResultListener {
onPositiveResult();
onNegativeResult();
}
private static ResultListener mResultListener;
public static setListener(ResultListener resultListener) {
mResultListener = resultListener;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && mResultListener != null) {
mResultListener.onPositiveResult();
} else if (resultCode == Activity.RESULT_CANCELED && mResultListener != null) {
mResultListener.onNegativeResult();
}
mResultListener = null;
}
}
public class MyService {
private MyActivity.ResultListener mListener = new MyActivity.ResultListener() {
onPositiveResult() {
// do something on RESULT_OK
}
onNegativeResult() {
// do something on RESULT_CANCELED
}
}
private void startActivityForResultFromHere() {
MyActivity.setListener(mListener);
Intent intent = new Intent();
intent.setClass(this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
As you can see I could not avoid static references due to device rotation issues, but I think this solution is more appropriate; albeit verbose.