Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close the activity from the service?

Tags:

android

I am launching activity from the service based on some value got from the server and the activity will be displayed for the some time and after getting close instruction from the server i need to close that activity,so for that i used following approach but it's not working: on Service class:

if(((ActivityManager)this.getSystemService(ACTIVITY_SERVICE)).getRunningTasks(1).get(0).topActivity.getPackageName().equals("com")) {

if(((ActivityManager)this.getSystemService(ACTIVITY_SERVICE)).getRunningTasks(1).get(0).topActivity.getClassName().equals("com.CustomDialogActivity")){
Intent dialogIntent = new Intent(getBaseContext(), CustomDialogActivity.class);
             dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);               
             dialogIntent.putExtra("description", "");
             dialogIntent.putExtra("cancelEnabled", false);
             dialogIntent.putExtra("close", true);
            getApplication().startActivity(dialogIntent);


}
    }

and on activity inside onCreate method:

Bundle bundle = getIntent().getExtras();
boolean isClosed = bundle.getBoolean("close");
    if(isClosed){        
        finish();
 }

I debugged it and found that control reaches to the onCreate method if(isClosed) condition and executed finish() method also but its not closing the activity.

so Couldn't be able to analyze what wrong I am doing.

like image 412
piks Avatar asked Nov 16 '11 09:11

piks


1 Answers

Write a broadcast receiver in your CustomDialogActivity like following.

private final BroadcastReceiver abcd = new BroadcastReceiver() {
             @Override
             public void onReceive(Context context, Intent intent) {
                   finish();                                   
             }
     };

Then register it in the same file like the following:

onCreate(){

    registerReceiver(abcd, new IntentFilter("xyz"));
}

Unregister it in onDestroy.

onDestroy(){

   //unRegister
}

Now,Whenever you want to close that Activity just call like the following.

sendBroadcast(new Intent("xyz"));

Hope this help.

like image 91
jainal Avatar answered Oct 24 '22 20:10

jainal