2016-12-27 1 views
0

나는이 내 응용 프로그램이 실행되는 동안 인터넷에 연결되어 있는지 여부를 확인하는 클래스 :확인 인터넷 연결

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

이 유 활동의 onResume에 수신기를 등록 했습니까? – rafsanahmad007

+0

아니, 어떻게해야합니까? 답을 쓸 수 있니? 나는 매니 페스트 파일에 등록하는 것을 의미하는 등록이라고 생각 했습니까? –

답변

0

아직도 당신이 시도 할 수

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

모든 활동에 대해이 작업을 수행해야합니까, 아니면 전체 응용 프로그램을 실행하는 일반적인 방법이 있습니까? –

+0

일반적으로 Application 클래스에 등록하여이 작업을 수행 할 수도 있습니다. 자세한 정보가있는 링크가 있습니다. http://stackoverflow.com/a/12834521/1967672 – tibbi

1

처럼 뭔가 명시 적에서 onCreate에서 정도를 등록해야합니다 :

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 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; 
    } 
} 

방송 수신기 정의를 이제 어떤 활동에서나 사용하십시오.

onPause에서 수신기 등록 취소
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()); 
} 

()

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

    } 
}