有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在按下后退按钮后立即进行方法调用(Android)

在给定的活动中,AlertDialog将用户带入WiFI设置。然后,用户按下后退按钮返回到所述活动

但是,只要按下后退按钮,我就需要进行方法调用。请注意,我不能简单地在活动中的以下代码之后添加方法,因为这将影响用户与AlertDialog实例交互的时间

方法调用需要在从WIFI设置菜单按下后退按钮后立即进行。请告诉我如何实施这一点

代码如下:

alertDialog.setPositiveButton("Settings", new dialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog, int which) {
          Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
          startActivity(intent);
         }
     });

共 (3) 个答案

  1. # 1 楼答案

    班级成员

    private static final int WIFI_REQUEST = 1234;
    

    使用startActivityForResult

    alertDialog.setPositiveButton("Settings", new dialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog, int which) {
          Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
          startActivityForResult(intent, WIFI_REQUEST);
         }
     });  
    

    在活动课上

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        super.onActivityResult(requestCode, resultCode, intent);
    
        switch (requestCode)
        {
             case WIFI_REQUEST:
                  // Call your method here
                  break;
        }
    }
    
  2. # 2 楼答案

    您可以Override调用ActivityonResume()方法。一旦用户按下“back”buttononResume()方法肯定会被调用,因此您应该能够将方法调用放在这里

  3. # 3 楼答案

    private boolean inwifisettings;
    
    public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
        inwifisettings = true;
        startActivity(intent);
    }
    
    @Override public void onWindowFocusChanged(boolean hasFocus)
    {
        if(inwifisettings & hasFocus)
        {
             doSomething();
             inwifisettings = false;
        }
    }
    

    为此,不应使用onResume()或startActivityForResult()/onActivityResult()。引用Android文档:http://developer.android.com/reference/android/app/Activity.html

    public void startActivityForResult (Intent intent, int requestCode, Bundle options)
    Note that this method should only be used with Intent protocols that are defined to return a result. In other protocols (such as ACTION_MAIN or ACTION_VIEW), you may not get the result when you expect. For example, if the activity you are launching uses the singleTask launch mode, it will not run in your task and thus you will immediately receive a cancel result.

    public void onWindowFocusChanged (boolean hasFocus)
    This is the best indicator of whether this activity is visible to the user.
    the system may display system-level windows (such as the status bar notification panel or a system alert) which will temporarily take window input focus without pausing the foreground activity.