How To Finish Activity From Service Class In Android?
I am developing one application in that i want to get data from server in background.I am getting data in background using service.Now i want to handle network exception,if no netw
Solution 1:
In line
((Activity) mContext).finish();
the mContext
is from new InitialRequestData(InitialRequestService.this).execute();
it is the InitialRequestService
, not Activity
,so u get a ClassCastExcetption.
You need to pass the Activity instance to Service. But I perfer to send a BroadcastReceiver
to Activity like this in your InitialRequestService
:
alert.setButton("OK", newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int which) {
alert.dismiss();
// modify hereLocalBroadcastManagerlocalBroadcastManager= LocalBroadcastManager
.getInstance(InitialRequestService.this);
localBroadcastManager.sendBroadcast(newIntent(
"com.durga.action.close"));
}
});
in Activity which you want to close:
publicclassYourActivityextendsActivity{
LocalBroadcastManager mLocalBroadcastManager;
BroadcastReceivermBroadcastReceiver=newBroadcastReceiver() {
@OverridepublicvoidonReceive(Context context, Intent intent) {
if(intent.getAction().equals("com.durga.action.close")){
finish();
}
}
};
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
IntentFiltermIntentFilter=newIntentFilter();
mIntentFilter.addAction("com.durga.action.close");
mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, mIntentFilter);
}
protectedvoidonDestroy() {
super.onDestroy();
mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
}
}
Hope it helps.
Solution 2:
I think you have to pass simple intent from service like following.
IntentmyIntent=newIntent(First.this,Secound.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
BundlemyKillerBundle=newBundle();
myKillerBundle.putInt("kill",1);
myIntent.putExtras(myKillerBundle);
getApplication().startActivity(myIntent);
Then in Secound.class
onCreate(Bundle bundle){
if(this.getIntent().getExtras().getInt("kill")==1)
finish();
}
Otherwise go with the BroadcastReceiver.see the example below.
How to close the activity from the service?
Hope it works.
Post a Comment for "How To Finish Activity From Service Class In Android?"