DurgaPrasad Ganti
DurgaPrasad Ganti

Reputation: 1008

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 network i want to show one alert dialog and finish application. Here i have problem that is finishing activity in service class shows exception ClassCastExcetption..Exception raised here(((Activity) mContext).finish())i tried so much but i unable get this please any one solve my problem

public class InitialRequestService extends Service{

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();   
        new InitialRequestData(InitialRequestService.this).execute();
    }   

    public class InitialRequestData extends AsyncTask<String, Void, Void> {

        public InitialRequestData(Context context) {
            this.mContext = context;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            isNetworkAvailable = CheckNetWork.isConnectedToInternet(mContext);
        }

        @Override
        protected Void doInBackground(String... params) {  
           //
        }

        @Override
        protected void onPostExecute(FeatureResult result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

            if(result==null || isNetworkAvailable==false){

                /*String message="Unable to connect to the server, please try again";
                FieldsValdations.AlertErrorMessage(mContext, message, "Network failure");*/

                final AlertDialog alert = new AlertDialog.Builder(mContext).create();
                alert.setTitle("Network failure"); 
                alert.setMessage("Unable to connect to the server, please try again");
                alert.setButton("OK", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {

                        alert.dismiss();
                        ((Activity) mContext).finish(); 
                    }
                });

            alert.setCancelable(false);
            alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            alert.show();
            }               
        }
    }
}

Upvotes: 17

Views: 21552

Answers (2)

Euporie
Euporie

Reputation: 1986

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", new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int which) {

        alert.dismiss();
        // modify here
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager
                .getInstance(InitialRequestService.this);
        localBroadcastManager.sendBroadcast(new Intent(
                "com.durga.action.close"));
                }
            });

in Activity which you want to close:

public class YourActivity extends Activity{

    LocalBroadcastManager mLocalBroadcastManager;
    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("com.durga.action.close")){
                finish();
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction("com.durga.action.close");
        mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, mIntentFilter);
    }

    protected void onDestroy() {
        super.onDestroy();
        mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
    }
}

Hope it helps.

Upvotes: 29

Born To Win
Born To Win

Reputation: 3329

I think you have to pass simple intent from service like following.

Intent myIntent = new Intent(First.this,Secound.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle myKillerBundle = new Bundle();
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.

Upvotes: 1

Related Questions