Android:如何等待方法完成再继续

时间:2019-06-27 14:34:53

标签: java android android-asynctask

我有一个名为getData()的方法,它在启动活动的早期加载;它基本上连接到json并从中检索一些字符串。

我有两个问题:

我的第一个问题是...此方法需要几秒钟的时间才能从json连接并检索数据,但是我的程序似乎没有等待并继续播放代码的下一行并同时运行getData()时间错了。我需要首先获取一些字符串,然后播放下一个代码。

我的第二个问题是,如果应用程序无法连接到json,我想再次调用getData()两次。如果连接成功,则可以使用布尔值isupdated来检查此值,该布尔值在getData()内部具有真实值。但是,再次调用方法getData()并等待它完成是不可能的。 这些方法都无济于事:

for(int x =0 , x<3 , x++ )
{
    if(!jsonfetch.isupdated) {jsonfetch.getData(splash.this)}
}

while (!jsonfetch.isupdated){
        jsonfetch.getData(splash.this);
    }

条件始终为假,它会同时调用该方法,因为它不会在再次检查条件之前等待它完成...

我尝试了很多解决方案,例如将getData()放在线程上并调用join(),但它没有等待。我也尝试过AsyncTask,但它在方法结束之前调用了onPostExecute(),我不理解。

以下是getData()代码

    public static void getData(final Context context) {
    handleSSLHandshake();
    requestQueue = Volley.newRequestQueue(context.getApplicationContext());
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, encryption.URL_main(), null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                Log.i("update_statut","Start Fetch .");
                popup_msg = jsonfect_Decryption(response.getString(encryption.epopup_msg));
                banner = jsonfect_Decryption(response.getString(encryption.ebanner));
                banner2= jsonfect_Decryption(response.getString(encryption.ebanner2));
                interstitial = jsonfect_Decryption(response.getString(encryption.einterstitial));
                interstitial_Inside = jsonfect_Decryption(response.getString(encryption.einterstitial_Inside));
                youtube_url = jsonfect_Decryption(response.getString(encryption.eyoutube_url));
                dialog_check = Boolean.parseBoolean(jsonfect_Decryption(response.getString(encryption.dialog_check)));
                dialog_Image_URL =jsonfect_Decryption(response.getString(encryption.dialog_Image_URL));
                dialog_URL = jsonfect_Decryption(response.getString(encryption.dialog_URL));
                dialog_txt= jsonfect_Decryption(response.getString(encryption.dialog_msg));
                dialog_canceble= Boolean.parseBoolean(jsonfect_Decryption(response.getString(encryption.dialog_canceble)));
                m3u_app_url = jsonfect_Decryption(response.getString(encryption.edownload_appurl));
                premium_url = jsonfect_Decryption(response.getString(encryption.emuimerp));
                premium_msg = jsonfect_Decryption(response.getString(encryption.epremium_msg));
                online_version=response.getString("ON_version");
                updated_version=response.getString("UP_version");
                url_version = jsonfect_Decryption(response.getString(encryption.eurl_version));
                activation = response.getString("act");

                isupdated=true;

                Log.i("update_statut","Ending Fetch .");

            } catch (JSONException e) {
                e.printStackTrace();
                Log.i("json",""+e.getMessage());
                isupdated=false;
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.i("json",""+error.getMessage());
            isupdated=false;
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/json");
            String creds = String.format("%s:%s",encryption.USERNAME(),encryption.Password());
            String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
            params.put("Authorization", auth);
            return params;

        }
    };
    requestQueue.add(jsonObjectRequest);
}

以下是飞溅活动

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Crashlytics());
    setContentView(R.layout._splash_java);


    /// Start Animation
    circle=(ImageView)findViewById(R.id.img_circle);
    textView2=(TextView) findViewById(R.id.textView2);
    txtwelcome=(TextView) findViewById(R.id.txtwelcome);
    relativeLayout=(RelativeLayout)findViewById(R.id.relativelayout);
    startAnimation();

    // GET DATABASE DATA
    while (!jsonfetch.isupdated){
        jsonfetch.getData(splash.this);
    }

    // Check Version

                    onlineVersion = jsonfetch.online_version;
                    updatedVersion = jsonfetch.updated_version;
                    try {
                        currentVersion = splash.this.getPackageManager()
                                .getPackageInfo(splash.this.getPackageName(), 0).versionName;
                    } catch (PackageManager.NameNotFoundException e) {
                        Log.d("update_statut", "currentVersion value is " + e.getMessage());
                    }

                    if ( onlineVersion == null || updatedVersion == null || onlineVersion.equals("null") || updatedVersion.equals("null")  ) {
                        Log.d("update_statut", "online_Version or updated_Version issue");
                        Log.d("update_statut", "Current version " + currentVersion + " & Online version " + onlineVersion + " & Updated version " + updatedVersion);
                        check_version = true;
                        jsonfetch.isupdated = false;
                    } else if ((currentVersion.equals(onlineVersion))) {
                        Log.d("update_statut", "match");
                        Log.d("update_statut", "Current version " + currentVersion + " & Online version " + onlineVersion);
                        check_version = true;
                        Interstitial_LOAD();
                    } else if ((currentVersion.equals(updatedVersion))) {
                        Log.d("update_statut", "match");
                        Log.d("update_statut", "Current version " + currentVersion + " & Updated version " + updatedVersion);
                        check_version = true;
                        Interstitial_LOAD();
                    } else {
                        Log.d("update_statut", "doesn't match");
                        Log.d("update_statut", "Current version " + currentVersion + " & Online version " + onlineVersion);
                        check_version = false;
                    }



    /// Load Next Activity after 5s so that Interstitial can be loaded


            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
            @Override
            public void run() {
            if(  (!check_version) && jsonfetch.isupdated){
                update_dialog();
                Log.d("update_statut", "Update dialog ");
            } else {
                Interstitial_SHOW();
            }
        }
    }, 5000);

}



private void Interstitial_LOAD()  {
    String inter_code = jsonfetch.interstitial;
    if ( inter_code!=null && !(inter_code.equals("null") || inter_code.equals("") )  ){
        AdRequest adRequestI = new AdRequest.Builder().build();
        interstitial = new InterstitialAd(this);
        interstitial.setAdUnitId(inter_code);
        interstitial.loadAd(adRequestI);
    }
}




    private void Interstitial_SHOW() {

    String inter_code = jsonfetch.interstitial;
    if ( inter_code!=null && !(inter_code.equals("null") || inter_code.equals("") )  )
    {
        if (interstitial.isLoaded())
        {
            interstitial.show();
            interstitial.setAdListener(new AdListener(){
                @Override
                public void onAdClosed() {
                    startActivity(new Intent(splash.this, first_java.class).setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
                    splash.this.finish();
                }
            });
        }
        else
        {
            startActivity(new Intent(splash.this, first_java.class).setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
            splash.this.finish();
        }
    }

    else {
        startActivity(new Intent(splash.this, first_java.class).setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
        splash.this.finish();
    }

}

1 个答案:

答案 0 :(得分:0)

关于您的第一次关注...

如果要暂停,请使用  java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

睡觉一秒钟或更长时间

TimeUnit.MINUTES.sleep(1);