2016-12-27 105 views
0

我有檢查,而我的應用程序運行在互聯網是否被連接的類:檢查Internet連接與廣播接收器不工作

public class NetworkChangeReciever extends BroadcastReceiver { 
@Override 
public void onReceive(Context context, Intent intent) { 

    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 

    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); 

    if (isConnected){ 
     Toast.makeText(context, "CONNECTED!", Toast.LENGTH_LONG).show(); 
    }else{ 
     Toast.makeText(context, "NOT CONNECTED", Toast.LENGTH_LONG).show(); 
    } 
}} 

我我的清單文件中添加了這個接收器,在應用程序中括號

 <receiver 
     android:name=".DataHelpers.NetworkChangeReciever"//DataHelpers is the package name 
     android:label="NetworkChangeReceiver"> 
     <intent-filter> 
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> 
      <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> 
     </intent-filter> 
    </receiver> 

現在我有點困惑。當我運行依賴互聯網的應用程序並關閉連接時,我是不是應該收到一條說「連接!」的Toast消息?接收器是否應該認識到沒有連接並且在我的NetworkChangerReciever類中觸發onReceive()方法?我在這裏錯過了什麼?謝謝。

+0

沒有ü註冊您的活動的接收器的onResume? – rafsanahmad007

+0

不,我該怎麼做?你能寫一個答案嗎?我認爲註冊意味着在清單文件中包含它? –

回答

0

你仍然有明確的的onCreate左右進行註冊,具有類似

registerReceiver(new NetworkChangeReciever(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); 
+0

我是否必須爲每項活動執行此操作,或者是否有通用的方法讓它在整個應用程序中運行? –

+0

通過將它註冊到Application類中,您也可以做到這一點。這裏有一些鏈接更多信息http://stackoverflow.com/a/12834521/1967672 – tibbi

1

你可以試試這個:

public class NetworkUtil { 

    public static int TYPE_WIFI = 1; 
    public static int TYPE_MOBILE = 2; 
    public static int TYPE_NOT_CONNECTED = 0; 

    public static int getConnectivityStatus(Context context) { 
     ConnectivityManager cm = (ConnectivityManager) context 
       .getSystemService(Context.CONNECTIVITY_SERVICE); 

     NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 
     if (null != activeNetwork) { 
      if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) 
       return TYPE_WIFI; 

      if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) 
       return TYPE_MOBILE; 
     } 
     return TYPE_NOT_CONNECTED; 
    } 

    public static String getConnectivityStatusString(Context context) { 
     int conn = NetworkUtil.getConnectivityStatus(context); 
     String status = null; 
     if (conn == NetworkUtil.TYPE_WIFI) { 
      status = "Wifi enabled"; 
     } else if (conn == NetworkUtil.TYPE_MOBILE) { 
      status = "Mobile data enabled"; 
     } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) { 
      status = "Not connected to Internet"; 
     } 
     return status; 
    } 
} 

定義廣播接收器:

public class NetworkChangeReceiver extends BroadcastReceiver { 

    public boolean isConnected = true; 
    String status; 
    Context Cnt; 
    Activity activity; 
    Activity parent; 
    AlertDialog alert; 


    public NetworkChangeReceiver(Activity a) { 
     // TODO Auto-generated constructor stub 
     parent = a; 
    } 

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

     activity = (Activity) context; 
     status = NetworkUtil.getConnectivityStatusString(context); 
     if (status.equals("Not connected to Internet")) { 
      //Toast.makeText(context, "Internet connection required", Toast.LENGTH_LONG).show(); 
     } 
     ReturnStatus(status, context); 
    } 

    public void ReturnStatus(String s, final Context cnt) { 
     if (s.equals("Mobile data enabled")) { 
      isConnected = true; 
      //Intent intent = new Intent(activity,activity.getClass()); 
      //activity.startActivity(intent); 

     } else if (s.equals("Wifi enabled")) { 
      isConnected = true; 

     } else { 
      isConnected = false; 
      final AlertDialog.Builder builder = new AlertDialog.Builder(cnt); 
      // Set the Alert Dialog Message 
      builder.setMessage("Internet connection required") 
        .setCancelable(false) 
        .setPositiveButton("continue", 
          new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, 
                int id) { 
            activity.finish(); 
            Intent intent = new Intent(activity, activity.getClass()); 
            activity.startActivity(intent); 
           } 
          }) 
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, 
              int id) { 
          if(alert.isShowing()) { 
           isConnected=false; 
           alert.dismiss(); 
          } 
         } 
        }); 

      alert = builder.create(); 
      alert.show(); 
     } 
    } 

    public boolean is_connected() { 
     return isConnected; 
    } 
} 

現在在任何活動中使用它們:

public NetworkChangeReceiver receiver; 
Boolean bl = true; 

public void checkInternet() { 
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); 
    receiver = new NetworkChangeReceiver(this); 
    registerReceiver(receiver, filter); 
    bl = receiver.is_connected(); 
    Log.d("Boolean ", bl.toString()); 
} 

取消註冊的onPause接收機()

@Override 
protected void onPause() { 
    super.onPause(); 
    try { 
     unregisterReceiver(receiver); 
    } catch (Exception e) { 

    } 
}