【问题标题】:Start another activity when detected network connection检测到网络连接时启动另一个活动
【发布时间】:2015-01-23 01:42:21
【问题描述】:

我目前正在做一个基于网络连接的项目。我正在开发一个定期检查网络连接的应用程序。如果没有连接,进度对话框应该旋转显示“无网络连接”,直到用户自己打开wifi 打开或任何其他类型的互联网连接。打开 wifi 后,如果应用程序与 wifi 连接,则进度对话框应关闭,控制应传递给另一个活动。我在谷歌搜索了很多次,但没有得到满意的答案。以下是我的代码:

     public class Alert extends Activity implements Runnable{


        ProgressDialog pd;
     WifiManager wm,wifiManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_alert);


        wm = (WifiManager) getSystemService(WIFI_SERVICE);

        if(!wm.isWifiEnabled()) {
        pd = ProgressDialog.show(this, "Network Error!!", "Network not found.Please make sure there is presence of any kind of network connection!!");

        Thread t = new Thread(this);
        t.start();  
        }
    }

    @Override
    protected void onResume() {

        super.onResume();

        if(wm.isWifiEnabled()) {
            pd.dismiss();
     Intent in=new Intent(Alert.this,WebPageView.class);
            startActivity(in);

        }
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

            while(wm.getWifiState() != 3) {

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            }
    }
 }

【问题讨论】:

    标签: java android eclipse networking android-studio


    【解决方案1】:
    To check network connection, use ConnectivityManager class.
    Add below method to your activity and call it to check network connection, if it returns true then it means network is available otherwise not.
    
    private boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    
    Now do it in your onCreate(...) method
    
    if(!isNetworkAvailable(Alert.this)) {
        pd = ProgressDialog.show(this, "Network Error!!", "Network not found.Please make sure there is presence of any kind of network connection!!");
        Thread t = new Thread(this);
        t.start();  
    }else{
        if(pd != null && pd.isShowing()){
            pd.dismiss();
        }
        Intent in=new Intent(Alert.this,WebPageView.class);
        startActivity(in);
    }
    
    Hope this will help you.
    

    【讨论】:

      【解决方案2】:

      使用 Handler 试试这样,它可能会工作。

      @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState); 
              setContentView(R.layout.activity_alert);
      
      
              wm = (WifiManager) getSystemService(WIFI_SERVICE);
      
              Handler handler = new Handler();
           handler.postDelayed(new Runnable() {
              public void run() {
              if(!wm.isWifiEnabled()) {
              runOnUiThread(new Runnable() {
                      public void run() {
                      if(pd == null)
                          pd = ProgressDialog.show(this, "Network Error!!", "Network not found.Please make sure there is presence of any kind of network connection!!");
                      }
                  });
      
              }else{
              runOnUiThread(new Runnable() {
                      public void run() {
                       if(pd != null)
                          pd.dismiss();
                       Intent in=new Intent(Alert.this,WebPageView.class);
                       startActivity(in); 
                      }
                  });
      
      
              }
              handler.postDelayed(this, 5000); //now is every 2 minutes
              }
           }, 5000);
      
          }
      

      【讨论】:

      • 在 5 秒的时间间隔内,它连续崩溃并自行打开,然后再次像循环一样崩溃
      • 我编辑了我的答案,你可以检查它并重播我。
      【解决方案3】:
        @Override
       public void run() {
         // TODO Auto-generated method stub
      
          while(running) {
      
              try {
        ConnectivityManager cm = (ConnectivityManager)
         context.getSystemService(Context.CONNECTIVITY_SERVICE);
              NetworkInfo info = cm.getActiveNetworkInfo();
              if (info != null) {
                  if (info.isConnected()) {
                      // you got a connection! tell your user!
                      Log.i("Post", "Connected");
                      running=false;
         runOnUiThread(new Runnable() {
      
            @Override
             public void run() {
          // TODO Auto-generated method stub
           pd.dismiss();
            }
              });
                      Intent intent_service=new Intent(this, anotherActivity.class);
                      context.startService(intent_service);
      
                  }
      
              } 
                  Thread.sleep(5000);
              } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
      
          }
      
          }
      

      【讨论】:

        【解决方案4】:

        把这个类放到你的项目中:

        public class Utility {
            public static boolean isNetworkConnected(Context context){
                boolean connected = false;
                ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                connected = (cm.getActiveNetworkInfo() != null&&cm.getActiveNetworkInfo().isAvailable() && cm
                    .getActiveNetworkInfo().isConnected());
                return connected;
            }
            public static void showAlert(final Activity activity, final String message,final String title) {
                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                builder.setMessage(message).setTitle(title).setCancelable(false)
                    .setNegativeButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id){
                            dialog.cancel();
                            activity.finish();
                        }
                    });
                AlertDialog alert = builder.create();
                alert.show();
            }
            public static void showAlertValidation(final Activity activity,final String message,final String title){
                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                builder.setMessage(message).setTitle(title).setCancelable(false)
                    .setNegativeButton("OK", new DialogInterface.OnClickListener(){
                        public void onClick(DialogInterface dialog,int id){
                            dialog.cancel();
                        }
                    });
                AlertDialog alert = builder.create();
                alert.show();
            }
        }
        

        此类检测您的互联网连接是否打开。之后,在您的活动中,输入以下代码:

            if(Utility.isNetworkConnected(Alert.this))
            {
        Intent in=new Intent(Alert.this,WebPageView.class);
                    startActivity(in);
        }
                    else if(!Utility.isNetworkConnected(Alert.this))
                        Utility.showAlert(Alert.this,"Internet Connection Not Present.","Network Error!");
        

        检查一下你的问题是否解决了。

        【讨论】:

          【解决方案5】:

          检查这个link

          取决于互联网状态的变化,您可以调用您的活动。

          希望这能解决您的问题

          【讨论】:

          • 看起来更像是评论而不是答案
          • 他定期检查互联网 wifi 或其他网络。瞬间,他可以检查互联网状态。这是检查互联网状态的正确方法。然后他可以调用特定的活动。
          猜你喜欢
          • 1970-01-01
          • 2016-09-19
          • 1970-01-01
          • 1970-01-01
          • 2019-02-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多