매번 연결을 확인하기 위해 브로드 캐스트를 사용하고 있습니다. 연결 정보에 대한 클래스를 만듭니다.
import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectivityStatus extends ContextWrapper{
public ConnectivityStatus(Context base) {
super(base);
}
public static boolean isConnected(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo connection = manager.getActiveNetworkInfo();
if (connection != null && connection.isConnectedOrConnecting()){
return true;
}
return false;
}
}
당신의 활동에 코드를 적용 :
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(!ConnectivityStatus.isConnected(getContext())){
// no connection
}else {
// connected
}
}
};
등록 방송을 활동의 onCreate()
방법 :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
..
...
....
}
를/등록 잊지 활동주기에 등록하지 마십시오
@Override
protected void onResume() {
super.onResume();
your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
@Override
protected void onPause() {
super.onPause();
your_activity_context.unregisterReceiver(receiver);
}
읽기 https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html#MonitorChanges –
나는이 질문에 6 개 이상의 답을 얻을 것이라고 확신한다 : 잠김 전에 D –
잃어 버렸다. 우리는 무엇을 베팅 했습니까? :) –