70 votes

Vérifiez la connexion internet d'INTENT

Y a-t-il un Android Intent ACTION_XXX qui me prévient lorsqu'une connexion Internet est disponible ?

Je veux instancier un BroadcastReceiver qui notifie mon application lorsqu'un utilisateur active la connexion Internet (par wifi, par GSM, etc.)

Quelqu'un peut-il m'aider ?

8voto

W4R10CK Points 4652

J'utilise le broadcast pour vérifier la connexion à chaque fois. Créer une classe pour les informations de connexion.

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

Appliquez le code dans votre activité :

 private BroadcastReceiver receiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
        if(!ConnectivityStatus.isConnected(getContext())){
            // no connection
        }else {
            // connected
        }
    }
 };

Enregistrer la diffusion dans le cadre de votre activité onCreate() méthode :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    ..
    ...
    ....
  }

N'oubliez pas de vous désinscrire/inscrire sur le cycle d'activité :

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

}

8voto

Nicky Points 613

Ce code fonctionnera (dans toutes les versions) car l'enregistrement du manifeste ne fonctionnera pas pour 7+(API 25 et plus) les appareils voient ceci lien .

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

6voto

JRE.exe Points 312

Réponse de Continuing meow mwo

vous pouvez activer/désactiver le récepteur en :

activer

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

désactiver

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

où, le même peut être appelé dans un Intent ou dans onCreate

3voto

razzak Points 2159

NetworkInfo.isConnected() est une méthode peu fiable pour tester l'état de l'Internet, elle renverra vrai lorsqu'il y a une connexion réseau, même s'il n'y a pas d'accès à l'Internet (ex. wifi sans Internet). Une approche plus fiable serait d'utiliser ping avec un 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;
}

2voto

Coldfin Lab Points 211
**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);
    }
}

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X