Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start an action on returning from settings screen android

My Scenario:

  1. I am opening an activity
  2. I am doing a validation(checking internet)
  3. On false of that validation, launching an alert dialog
  4. Now I go to settings enable internet comeback by pressing back button
  5. The dialog is not dismissed it still is in the screen
  6. My objective is to restart the activity when i return from settings screen

CODE

public void open(){
        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage(getApplicationContext().getResources().getString(R.string.searchFilterLocationMessage));
        alertDialogBuilder.setPositiveButton(R.string.Ok, 
                new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                /*Intent intent = new Intent(Settings.ACTION_SETTINGS) ;
                this.startActivity(intent);
                 */
                startActivityForResult(new Intent(Settings.ACTION_SETTINGS), 0);


            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 0) {
            Intent intent = getIntent();
        finish();
        startActivity(intent);
        }
    }//onActivityResult
like image 589
Devrath Avatar asked Dec 19 '14 14:12

Devrath


2 Answers

Launching an Activity whith the singleTask launch mode by calling startActivityForResult(intent, requestCode) returns a cancel result immediately. You can see it in debugger that onActivityResult() is called even before the system settings Activity starts.

As a quick workaround I suggest using a flag indicating whether the settings Activity was called or not. Like

  1. setting a flag

    private boolean flag = false;
    
  2. using startActivity() istead of startActivityForResult()

    @Override
    public void onClick(DialogInterface arg0, int arg1) {
        startActivity(new Intent(Settings.ACTION_SETTINGS));
        flag = true;
    }
    
  3. checking the flag in onResume()

    @Override
    protected void onResume(){
    super.onResume();
        if (flag) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }
    
like image 154
Onik Avatar answered Sep 26 '22 04:09

Onik


Launch the setting intent:

startActivity(new Intent(Settings.ACTION_SETTINGS));

and fetch the current Activity in onResume() method:

public void onResume(){
    super.onResume();
    // Do your work
}

After getting back from the setting screen, your onResume() method will be call and here you can fetch your location.

like image 44
XH6 user Avatar answered Sep 23 '22 04:09

XH6 user