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

后端 未结 3 1034
花落未央
花落未央 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:27

    you can create a Service class and use TimerTask with Timer and give it a duration to start over, with this you can start your service from the receiver that you already have and make it (receiver) listen to BOOT_COMPLETED with

    
        
    
    

    and specify a permission

    and let your receiver call the service class -(or you can check your stuff there -(take into consideration the comments i made)) by implementing this in your onReceive

    boolean isMyServiceRunning(Class serviceClass, Context t) {
        ActivityManager manager = (ActivityManager) t.getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    

    and if it returns false start service using

    Intent i = new Intent(context, MyService.class);
    context.startService(i);
    

    then in your service do this

    public class MyService extends Service {
    Timer timer; TimerTask task;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
    
        timer = new Timer();
        task = new TimerTask() {  
          @Override                 
          public void run() { 
              // put here your code for checking 
    
              String status = NetworkUtil.getConnectivityStatusString(context);
              // i am having nesting problems so put this in a handler() ok
              Toast.makeText(context, status, Toast.LENGTH_LONG).show();
              if(status.equals("Not connected to Internet")) {
              Intent splashIntent = new Intent(context, SplashScreen.class);
              splashIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              context.startActivity(splashIntent);  
               }
            // handler() code should end here           
         };                             
        timer.schedule(task, 0, 3000);  // repeat every 3 seconds
    
        return START_STICKY;
      }
    }
    

    its getting long, to close your splash screen, you can pass an instance of your activity and make it close itself from the service, or bind to the service or use local broadcast manager

    also my code closing tags might be wrong so correct them..

提交回复
热议问题