如何正确延迟方法?

时间:2016-01-18 17:58:37

标签: android wait thread-sleep

我试图运行2种方法,但不是同时运行。不过,我已经尝试了waitThread.sleep(),但它并没有延迟方法2 Intent

 public void run() {
    checkInternetConnection();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    Intent intent = new Intent(this, Forside.class);
    startActivity(intent);
    finish();
}
private void checkInternetConnection() {

    if (br == null) {

        br = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                Bundle extras = intent.getExtras();

                NetworkInfo info = (NetworkInfo) extras
                        .getParcelable("networkInfo");

                NetworkInfo.State state = info.getState();
                Log.d("TEST Internet", info.toString() + " "
                        + state.toString());

               if(state == NetworkInfo.State.DISCONNECTED) {
                    AlertDialog alert = new AlertDialog.Builder(context)
                            .setMessage("Fejl, der er ingen internet forbindelse. Venligst forbind til et netværk")
                            .setNeutralButton("ok", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            launchsettings();
                                        }

                                    }
                            ).show();
                }
            }
        };

        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver((BroadcastReceiver) br, intentFilter);
    }
}

private void launchsettings() {
    startActivityForResult(new Intent(Settings.ACTION_SETTINGS), 0);
}

@Override
protected void onPause() {
    this.unregisterReceiver(this.bur);
    super.onPause();
}

两种方法同时开始,或者2.方法直接在1之后开始。

1 个答案:

答案 0 :(得分:0)

创建一个像这样的函数

public static boolean isInternetConnected(Context context)
{
    boolean result = false;
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info != null)
    {
        result = info.isConnected();
        Log.i("My Project", "Connected NetworkType: " + info.getTypeName());
    }
    return result;
}

然后在你的活动中做这个

if(isInternetConnected()){
 //TODO
}else{
 //TODO
}