Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to finish activity from service class in android?

Tags:

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();
            }               
        }
    }
}
like image 493
Durga Avatar asked Sep 15 '14 05:09

Durga


People also ask

How to Finish activity in Android?

On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.

How do I stop a service from activity?

On your Android phone or tablet, go to myactivity.google.com. Above your activity, tap Delete . Tap All time.


2 Answers

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.

like image 120
Euporie Avatar answered Oct 12 '22 12:10

Euporie


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.

like image 30
Born To Win Avatar answered Oct 12 '22 13:10

Born To Win