Thank you for your solution.
I faced the same problem and worked out with your help.
I put this answer just to share my way for passing result back to the service.
I didn't create any additional custom intent class and solved the result passing problem by only Intent.putExtra()
methods with some tricks.
In the service, use this code to start the DialogActivity
which display the alert dialog in onCreate()
.
Intent intent = new Intent(this.getApplicationContext(), DialogActivity.class);
intent.putExtra(DialogActivity.CLASS_KEY, this.getClass().getCanonicalName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
And in the DialogActivity
, finish it like this:
private void returnOk(boolean ok) {
Intent srcIntent = this.getIntent();
Intent tgtIntent = new Intent();
String className = srcIntent.getExtras().getString(CLASS_KEY);
Log.d("DialogActivity", "Service Class Name: " + className);
ComponentName cn = new ComponentName(this.getApplicationContext(), className);
tgtIntent.setComponent(cn);
tgtIntent.putExtra(RESULT_KEY, ok ? RESULT_OK : RESULT_CANCEL);
this.startService(tgtIntent);
this.finish();
}
At last, in the service, override the onStartCommand()
method and get the result from the intent.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int ret = super.onStartCommand(intent, flags, startId);
Bundle extras = intent.getExtras();
if (extras != null) {
int result = extras.getInt(DialogActivity.RESULT_KEY, -1);
if (result >= 0) {
if (result == DialogActivity.RESULT_OK) {
// Your logic here...
}
} else {
// Your other start logic here...
}
}
return ret;
}
I am not sure whether this way is a good solution, at least it works for me. Hope this will be helpful for someone else like me.
The complete source can be found here: