ANDROID Show a dialog when the Internet/GPS loses connectivity or is not connected

后端 未结 3 1036
花落未央
花落未央 2021-01-29 00:02

[EDITED]

I want to show a Splash Screen / dialog when the Internet or GPS is down or not connected so the user can\'t use the app until the connection is good again.

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-29 00:42

    STEP 1: Open AndroidManifest.xml and add the broadcast receiver.

    
            
                
                
                
            
        `
    

    STEP 2: create activity with dialog theme:

    
    

    STEP 3: Make a BroadcastReceiver Class named InternetConnectorReceiver

    public class InternetConnectorReceiver extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
        if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED) ||
                intent.getAction().equalsIgnoreCase("android.net.conn.CONNECTIVITY_CHANGE")) {
            Intent checkIntent = new Intent(context, ConnectivityCheck.class);
            context.startService(checkIntent);
        }
    }}
    

    STEP 4: Make another service class named ConnectivityCheck :

    public class ConnectivityCheck extends Service {
    
    @Override
    public void onCreate() {
        super.onCreate();
        if (!checkConnection()) {
            Toast.makeText(context, "off", Toast.LENGTH_LONG).show();
            Intent dialogIntent = new Intent(this, ActivityDialogInternet.class);
            dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(dialogIntent);
        }
        stopSelf();
    }
    
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    private boolean checkConnection() {
        Log.i("wudfuyf", "checking started!!!!!!!!!!!!!!!!!!");
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();
    
    }}
    

    STEP 5: create a activity called ActivityDialogInternet

    public class ActivityDialogInternet extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog_internet);
    }}
    

    STEP 6: When internet connection is turned off ActivityDialogInternet called and show the dialog:

提交回复
热议问题