在SplashScreen期间检查Internet

时间:2016-06-01 20:29:41

标签: android android-layout splash-screen android-internet

好吧,在SplashScreen屏幕之后。我的应用程序将检查Internet连接。如果有可用的互联网,它将调用WebView。否则,它将调用一个错误活动。

但是如何在SplashScreen中配对以检查互联网?

ACTIVITY SPLASH SCREEN:

public class Splash extends Activity{

    private static int tempo_splash = 1000;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Para o layout preencher toda tela do cel (remover a barra de tit.)

        new Timer().schedule(new TimerTask() {

            public void run() {
                finish();

                Intent intent = new Intent();
                intent.setClass(Splash.this, MainActivity.class); //Chamando a classe splash e a principal (main)
                startActivity(intent);
            }
        }, 2000);

    }

}

MY CLASS CheckINTERNET:

public class CheckInternet extends Activity{

    boolean status = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.internet);

        Button btnStatus = (Button) findViewById(R.id.check_btn);
        btnStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status = checkInternetConnection();

                if (status) {

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            final Intent mainIntent = new Intent(CheckInternet.this, MainActivity.class);
                            CheckInternet.this.startActivity(mainIntent);
                            CheckInternet.this.finish();
                        }
                    }, 5000);

                }
                else {
                    Toast.makeText(getApplicationContext(), "You don't have Internet connection. Try Again", Toast.LENGTH_LONG).show();

                }
            }
        });
    }


    public boolean checkInternetConnection() {

        ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivity != null) {
            NetworkInfo[] inf = connectivity.getAllNetworkInfo();
            if (inf != null) {
                for (int i = 0; i < inf.length; i++) {
                        return true;
                }
            }
        }
        return false;
    }

}

6 个答案:

答案 0 :(得分:3)

试试这段代码......也许可以帮到你

public class SplashScreen extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.splash_screen);

    if(isWorkingInternetPersent()){
        splash();
    }
    else{
        showAlertDialog(SplashScreen.this, "Internet Connection",
                "You don't have internet connection", false);
    }
}
public void splash() {
    Thread timerTread = new Thread() {
        public void run() {
            try {
                sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                Intent intent = new Intent(getApplicationContext(), New_Main_Activity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
            }
        }
    };
    timerTread.start();
}
public boolean isWorkingInternetPersent() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getBaseContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }

    }
    return false;
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    // Setting alert dialog icon
    // alertDialog.setIcon((status) ? R.mipmap.ic_launcher : R.mipmap.ic_launcher);

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

            finish();
            System.exit(0);
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

答案 1 :(得分:0)

你不应该只是为了检查连接而有一个Intent。我的建议是创建一个“实用程序”类 - 调用MyConnectivityChecker并在那里使用以下代码添加静态方法(isConnected):

    public class MyConnectivityChecker {

        public static boolean  isConnected(Context context){
         boolean connected = false;
         ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
         NetworkInfo mobile = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);        
         connected = (wifi.isAvailable() && wifi.isConnectedOrConnecting() || (mobile.isAvailable() && mobile.isConnectedOrConnecting()));
         return connected;
    }
}

然后在Splash活动中,无论您想要检查连接性,都可以像这样调用isConnected方法:

MyConnectivityChecker.isConnected(this)

例如,您可以这样做:

if(MyConnectivityChecker.isConnected(this)){
//connectivity available
}
else{
 //no connectivity
}

我希望这会有所帮助。试一试,让我知道。

答案 2 :(得分:0)

您可以做的是检查SplashScreen计时器内的互联网连接。

new Timer().schedule(new TimerTask() {

    public void run() {
        if(isOnline()){

            Intent intent = new Intent(Splash.this,WebViewActivity.class);
            startActivity(intent);
            finish();

        }else{

             Intent intent = new Intent(Splash.this,ErrorActivity.class);
             startActivity(intent);
             finish();

        }
    }
}, 2000);

对于互联网检查,您可以使用此方法。

public boolean isOnline() {
    System.out.println("executeCommand");
    Runtime localRuntime = Runtime.getRuntime();
    try {
        int i = localRuntime.exec("/system/bin/ping -c 1 8.8.8.8")
                .waitFor();
        System.out.println(" mExitValue " + i);
        boolean bool = false;
        if (i == 0) {
            bool = true;
        }
        return bool;
    } catch (InterruptedException localInterruptedException) {
        localInterruptedException.printStackTrace();
        System.out.println(" Exception:" + localInterruptedException);
        return false;
    } catch (IOException localIOException) {
        localIOException.printStackTrace();
        System.out.println(" Exception:" + localIOException);
    }
    return false;
} 

注意:onCreate()方法之外的SplashScreen中添加此方法。

快乐编码..

答案 3 :(得分:0)

创建以下实用程序类:

public class Utility {

/**
     * This function check <u>Mobile Data</u> or <u>WiFi</u> is switched on or not..<br />
     * It will be return <b>true</b> when switched on and return <b>false</b> when switched off.<br />
     * <br />
     * Developed by <b><a href="http://about.me/SutharRohit">Suthar Rohit</a></b>
     *
     * @param context {@link Context} of activity
     * @return true if <u>Mobile Data</u> or <u>WiFi</u> is switched on.
     */
    public static boolean isOnline(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo nInfo = cm.getActiveNetworkInfo();
            return nInfo != null && nInfo.isConnected();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

并在启动画面中使用如下:

if(Utility.isOnline()) {
     // INTERNET AVAILABLE

} else {
     // INTERNET NOT AVAILABLE
}

答案 4 :(得分:0)

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;

public class SplashACtivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                NetworkInfo activeNetwork = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
                        .getActiveNetworkInfo();

                if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {

                    // Load Webview
                    startActivity(new Intent(SplashACtivity.this, WebViewActivity.class));
                } else {

                    // Show No internet
                    startActivity(new Intent(SplashACtivity.this, NoInternetACtivity.class));
                }
            }
        }, 5000);
    }
}

答案 5 :(得分:0)

尝试使用此代码:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ApplicationUtility {
   ConnectivityManager connectivityManager;
   NetworkInfo info;

public boolean checkConnection(Context context) {
    boolean flag = false;
    try {
        connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        info = connectivityManager.getActiveNetworkInfo();

        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            System.out.println(info.getTypeName());
            flag = true;
        }
        if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            System.out.println(info.getTypeName());
            flag = true;
        }
    } catch (Exception exception) {
        System.out.println("Exception at network connection....."
                + exception);
    }
    return flag;
}}

对于启动屏幕活动:

import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class Splash extends Activity {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);

    Timer t = new Timer();
    boolean checkConnection=new ApplicationUtility().checkConnection(this);
    if (checkConnection) {
        t.schedule(new splash(), 3000);
    } else {
        Toast.makeText(Splash.this,
                "connection not found...plz check connection", 3000).show();
    }
}

class splash extends TimerTask {

    @Override
    public void run() {
        Intent i = new Intent(Splash.this,LoginActivity.class);
        finish();
        startActivity(i);
    }

}

}