Nice programing

INTENT 인터넷 연결 확인

nicepro 2020. 11. 2. 19:40
반응형

INTENT 인터넷 연결 확인


Intent ACTION_XXX인터넷 연결이 가능할 때 알려주 는 Android 가 있습니까?

BroadcastReceiver사용자가 인터넷 연결 (WiFi, GSM 등)을 활성화 할 때 내 애플리케이션에 알리는를 인스턴스화하고 싶습니다 .

누구든지 나를 도울 수 있습니까?


<receiver android:name=".YOURRECEIVER">
   <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

수락 된 답변이 정확합니다. 완료를 위해 수신자 코드 만 추가합니다.

public class NetworkStateReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
     Log.d("app","Network connectivity change");
     if(intent.getExtras()!=null) {
        NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
        if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
            Log.i("app","Network "+ni.getTypeName()+" connected");
        } else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
            Log.d("app","There's no network connectivity");
        }
   }
}

@lujop 답변 업데이트 :

public class NetworkStateReceiver extends BroadcastReceiver {
    private static final String TAG = "NetworkStateReceiver";

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

        Log.d(TAG, "Network connectivity change");

        if (intent.getExtras() != null) {
            final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();

            if (ni != null && ni.isConnectedOrConnecting()) {
                Log.i(TAG, "Network " + ni.getTypeName() + " connected");
            } else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
                Log.d(TAG, "There's no network connectivity");
            }
        }
    }
}

MyReceiver.java

public class MyReceiver extends BroadcastReceiver{

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

        if(isConnected(context)) Toast.makeText(context, "Connected.", Toast.LENGTH_LONG).show();
        else Toast.makeText(context, "Lost connect.", Toast.LENGTH_LONG).show();
    }

    public boolean isConnected(Context context) {
        ConnectivityManager cm =
                (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                              activeNetwork.isConnected();
        return isConnected;
    }
}

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

최신 정보

앱이 API 레벨 26 이상을 대상으로하는 경우 해당 제한에서 제외 된 몇 가지 암시 적 브로드 캐스트를 제외하고는 매니페스트를 사용하여 암시 적 브로드 캐스트 (앱을 구체적으로 대상으로 지정하지 않는 브로드 캐스트)에 대한 수신기를 선언 할 수 없습니다. 대부분의 경우 예약 된 작업을 대신 사용할 수 있습니다.

용법 connection = MyReceiver()

// onCreate - onDestroy, onResume - onPause depends on you
override fun onStart() {
    super.onStart()
    registerReceiver(connection, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
  }

override fun onStop() {
    super.onStop()
    // remember unregister to avoid leak
    unregisterReceiver(connection)
  }

업데이트 2

CONNECTIVITY_ACTION이 상수는 28 애플 리케이션 더 다양한 사용해야 API 수준에서 사용되지 않습니다 requestNetwork(NetworkRequest, PendingIntent), registerNetworkCallback(NetworkRequest, PendingIntent)또는 registerDefaultNetworkCallback(ConnectivityManager.NetworkCallback)네트워크가 그들에 대해 관심이 변경 사항에 대한보다 신속하고 자세한 업데이트 대신 기능을.

왜냐하면 added in API level 22위의 코드는 모든 버전의 안드로이드에서 잘 작동 하기 때문 입니다.


모든 답변에서 누락 된 부분은 해당 작업에 등록하라는 알림입니다.

IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(your_receiver, filter);

7+ (API 25 이상) 기기 에서는 매니페스트 등록이 작동하지 않으므로이 코드는 모든 버전에서 작동합니다 (링크 참조 ) .

private void foo(){
    registerReceiver(connectionBroadcastReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}

private BroadcastReceiver connectionBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || intent.getExtras() == null)
           return;

        ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {  
            // connected
        } 
    }
};

매번 연결을 확인하기 위해 브로드 캐스트를 사용하고 있습니다. 연결 정보에 대한 클래스를 만듭니다.

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

}

계속 meow mwo의 답변

다음과 같이 수신기를 활성화 / 비활성화 할 수 있습니다.

활성화

 ComponentName receiver = new ComponentName(MainActivity.this, MyReceiver.class);
       PackageManager pm = this.getPackageManager();
       pm.setComponentEnabledSetting(receiver,
               PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
               PackageManager.DONT_KILL_APP);
       Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();
   }

비활성화

ComponentName receiver = new ComponentName(MainActivity.this, MyReceiver.class);
       PackageManager pm = this.getPackageManager();
       pm.setComponentEnabledSetting(receiver,
               PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
               PackageManager.DONT_KILL_APP);
       Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();
   }

여기서 Intent 또는 onCreate에서 동일한 것을 호출 할 수 있습니다.


NetworkInfo.isConnected()인터넷 상태를 테스트하는 신뢰할 수없는 방법입니다. 인터넷에 액세스 할 수없는 경우에도 네트워크에 연결되어 있으면 true를 반환합니다 (예 : 인터넷이없는 wifi). 보다 안정적인 접근 방식은 다음 ping과 함께 사용 하는 것입니다 CONNECTIVITY_ACTION BroadcastReceiver.

private void registerInternetReceiver()
{
    if (this.internetReceiver != null) return;
    this.internetReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive (Context context, Intent intent)
        {
            if (isInternetAvailable()) Log.i ("Tag", "internet status online");
            else Log.i ("Tag", "internet status offline");
        }
    };
    IntentFilter filter = new IntentFilter();
    filter.addAction (ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver (internetReceiver, filter);
}

private boolean isInternetAvailable()
{
    try
    {
        return (Runtime.getRuntime().exec ("ping -c 1 google.com").waitFor() == 0);
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
    return false;
}

**Also worked on above Android 7.0**

// AndroidManifest.xml

 <service
            android:name=".NetworkSchedulerService"
            android:exported="true"
            android:permission="android.permission.BIND_JOB_SERVICE"/>


// MyApplication.java           

import  android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
public class MyApplication extends Application {

    private static Context context;

    public static Context getContext() {
        return context;
    }

    public static final String TAG = MyApplication.class.getSimpleName();

    private static MyApplication mInstance;


    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        mInstance = this;
        scheduleJob();
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    private void scheduleJob()
    {
        JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
                .setRequiresCharging(true)
                .setMinimumLatency(1000)
                .setOverrideDeadline(2000)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .setPersisted(true)
                .build();

        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        assert jobScheduler != null;
        jobScheduler.schedule(myJob);
    }
}   


// Constants.java   

public class Constants {
    public static final String CONNECT_TO_WIFI = "WIFI";
    public static final String CONNECT_TO_MOBILE = "MOBILE";
    public static final String NOT_CONNECT = "NOT_CONNECT";
    public final static String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
}


// LiveConnectivityReceiver.java    

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class LiveConnectivityReceiver extends BroadcastReceiver {

    private MConnectivityReceiver mConnectivityReceiver;
    LiveConnectivityReceiver(MConnectivityReceiver listener) {
        mConnectivityReceiver = listener;
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        mConnectivityReceiver.onNetworkConnectionChanged(isConnected(context));

    }

    public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        assert cm != null;
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    public interface MConnectivityReceiver {
        void onNetworkConnectionChanged(boolean isConnected);
    }
}   


// MainActivity.java    

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private BroadcastReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    protected void onStop() {
        stopService(new Intent(this, NetworkSchedulerService.class));
        super.onStop();
    }

    @Override
    protected void onStart() {
        super.onStart();
        startService( new Intent(this, NetworkSchedulerService.class));
    }


    @Override
    protected void onPause() {
        super.onPause();
        this.unregisterReceiver(this.mReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter("android.intent.action.MAIN");
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                boolean isConnection = intent.getBooleanExtra("VALUE", false);
                if (!isConnection) {
                    Toast.makeText(context, "No Internet Connection", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Back to online", Toast.LENGTH_SHORT).show();
                }
            }
        };
        this.registerReceiver(mReceiver, intentFilter);
    }
}   


// NetworkSchedulerService.java 


import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.content.IntentFilter;

public class NetworkSchedulerService extends JobService implements LiveConnectivityReceiver.ConnectivityReceiverListener 
{

    private LiveConnectivityReceiver mLiveConnectivityReceiver;

    @Override
    public void onCreate()
    {
        super.onCreate();
        mLiveConnectivityReceiver = new LiveConnectivityReceiver(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        registerReceiver(mLiveConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION));
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        unregisterReceiver(mLiveConnectivityReceiver);
        return true;
    }

    @Override
    public void onNetworkConnectionChanged(boolean isConnected)
    {
        Intent broadcastedIntent=new Intent("android.intent.action.MAIN");
        broadcastedIntent.putExtra("VALUE", isConnected);
        sendBroadcast(broadcastedIntent);
    }
}

Android 7 ++에서는 @fedj의 답변이 작동하지 않지만 방송 수신기를 프로그래밍 방식으로 등록 할 수 있습니다.

Android 7.0 (API 레벨 24) 이상을 대상으로하는 앱은 manifest에서 broadcast receiver를 선언하는 경우 CONNECTIVITY_ACTION 브로드 캐스트를 수신하지 않습니다. 앱이 BroadcastReceiver를 Context.registerReceiver ()에 등록하고 해당 컨텍스트가 여전히 유효한 경우 앱은 CONNECTIVITY_ACTION 브로드 캐스트를 계속 수신합니다.


I would read the docs updated for nougat + , because intent is deprecated due to the # of devices, network info alone is not sufficient. I would use connectivity manager ( connectivity action, add variables there) commands and vars there, because most has changed in the last year alone, and on for testing, enable cell data always active, verbose logging and aggressive handover, use wlan filter if needed:

https://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION

참고URL : https://stackoverflow.com/questions/3767591/check-intent-internet-connection

반응형