2016-12-27 12 views
0

I持って自分のアプリケーションを実行しながら、インターネットが接続されているかどうかをチェックするクラス:インターネット接続チェック

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> 

今はちょっと混乱しています。インターネットに依存している接続を遮断しているアプリケーションを実行すると、「接続済み」というトーストメッセージが表示されませんか?受信機は接続がないことを認識し、NetworkChangerRecieverクラスのonReceive()メソッドを起動しないでください。私はここで何が欠けていますか?ありがとうございました。

+0

uがアクティビティの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) { 

    } 
} 
関連する問題