J'ai créé un code qui vérifie la connexion Internet au début, mais je veux qu'il continue à vérifier la connexion Internet en arrière-plan et informe l'utilisateur lorsque la connexion est perdue. Je suis nouveau sur Android alors pouvez-vous s'il vous plaît écrire le code approprié et m'aider. Ce code fonctionne bien, je veux juste qu'il fonctionne en arrière-plan pour garder un contrôle sur Internet.
public class isNetworkAvailable extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_is_network); ; if(!isNetworkAvailable()){ //Create an alert dialog AlertDialog.Builder Checkbuilder = new AlertDialog.Builder(isNetworkAvailable.this); Checkbuilder.setIcon(R.drawable.error); Checkbuilder.setTitle("Error!"); Checkbuilder.setMessage("Check Your Internet Connection."); //Builder Retry Button Checkbuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { //Restart The Activity Intent intent = getIntent(); finish(); startActivity(intent); } }); Checkbuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) ; AlertDialog alert=Checkbuilder.create(); alert.show(); } else { if (isNetworkAvailable()){ Thread tr=new Thread(){ public void run(){ try { sleep(4); } catch (Exception e){ e.printStackTrace(); } finally { Intent i = new Intent(isNetworkAvailable.this,MainActivity.class); startActivity(i); finish(); }}};tr.start();}}}private boolean isNetworkAvailable(){ ConnectivityManager connectivityManager=(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo=connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo !=null; } }
7 Réponses :
Vous pouvez utiliser ScheduledExecutorService pour planifier une action à intervalles réguliers sur un thread d'arrière-plan. vérifier toutes les secondes:
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate (new Runnable() { public void run() { //above method } }, 0, 1, TimeUnit.SECONDS);
Comme:
public boolean isInternetAvailable() { try { InetAddress ipAddr = InetAddress.getByName("google.com"); return !ipAddr.equals(""); } catch (Exception e) { return false; } }
démarrer un service et faire ceci.
Essayez ceci: ajoutez ce code dans OnCreate()
/*--Check Connectivity--*/ private BroadcastReceiver mConnReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { /* boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);*/ NetworkInfo currentNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); // NetworkInfo otherNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO); if (currentNetworkInfo.isConnected()) { if (check) Snackbar.make(viewPager, "Connected :) ", Snackbar.LENGTH_LONG).show(); } else { //Toast.makeText(WikiSnapActivity.this, "Not Connected", Toast.LENGTH_LONG).show(); Snackbar.make(viewPager, "No Internet :( ", Snackbar.LENGTH_INDEFINITE).show(); check = true; } } };
Appelez cette méthode
/*--Check Connectivity--*/ getApplicationContext().registerReceiver(mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
Son autre solution, vous pouvez mettre ce code dans l'activité où vous souhaitez continuer à vérifier la connexion Internet.
Utilisez le fichier BroadCast Receiver Create Class et enregistrez-le dans AndroidManifest.xml en tant que récepteur et étendez BroadcastReceiver Class.
AndroidManifest.xml
public boolean isOnline(Context context) { ConnectivityManager cMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo nInfo = cMan.getActiveNetworkInfo(); return (nInfo != null && nInfo.isConnected()); }
Et dans la méthode onReceive () utilisez la méthode ci-dessous pour vérifier la connexion Internet.
<receiver android:name=".CheckConnection" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver>
Utilisez ReactiveNetwork lib
ReactiveNetwork em> est une bibliothèque Android écoutant l'état de la connexion réseau et la connectivité Internet. La bibliothèque prend en charge les stratégies de surveillance de réseau nouvelles et héritées. Version minimale du SDK = 9
Utilisation
ajoutez ceci à gradle
ReactiveNetwork.observeInternetConnectivity() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(isConnectedToInternet -> { // do something with isConnectedToInternet value changeOnlineStatus(isConnectedToInternet ? ConnectionQuality.EXCELLENT : ConnectionQuality.POOR); });
et à votre activité
dependencies { implementation 'com.github.pwittchen:reactivenetwork-rx2:3.0.2' }
it Observez en permanence la connectivité Internet
pour plus d'informations lien
Qu'est-ce que ConnectionQuality.EXCELLENT
? Comment définissez-vous cela?
c'est juste une énumération
avec 2 valeurs
fichier java, cela vérifiera la présence d'Internet lorsque l'application démarrera. et ajoutez simplement cette ligne de code vérifiera la connexion Internet en continu et votre mainfest Android devrait être comme ça placer ce fichier sous les éléments avec le nom error.html vous devez saisir tout le code ci-dessus pour que cela fonctionne correctement. j'espère que cela vous aidera <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<title>No Connection</title>
<!-- Stylesheets-->
<style type="text/css">
body{
background: #E1e1e1;
}
#cloud{
width: 300px;
height: 120px;
background: #676767;
background: -webkit-linear-gradient(-90deg,#676767 5%, #676767 100%);
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
border-radius: 100px;
position: relative;
margin: 150px auto 0;
opacity: .5;
}
#cloud:before, #cloud:after{
content: '';
position:absolute;
background: #676767;
z-index: -1;
}
#cloud:after{
width: 100px;
height: 100px;
top: -50px;
left:50px;
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
border-radius: 100px;
}
#cloud:before{
width: 120px;
height: 120px;
top: -70px;
right: 50px;
-webkit-border-radius: 200px;
-moz-border-radius: 200px;
border-radius: 200px;
}
.shadow {
width: 300px;
position: absolute;
bottom: -10px;
background: black;
z-index: -1;
-webkit-box-shadow: 0 0 25px 8px rgba(0,0,0,0.4);
-moz-box-shadow: 0 0 25px 8px rgba(0,0,0,0.4);
box-shadow: 0 0 25px 8px rgba(0,0,0,0.4);
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
}
h1{
color: #fff;
font-size: 25px;
padding-top: 1px;
text-align: center ;
margin: 2px auto;
}
h2 {
color: #fff;
font-size: 17px;
padding-top: 15px;
text-align: center;
margin: 5px auto;
}
h4 {
color: #fff;
font-size: 14px;
margin: 0 auto;
padding: 0;
text-align: center;
}
</style>
<body>
<div id="cloud"><h1>Whoops!</h1>
<h2>Slow or No internet Connection :(</h2>
<h4>Please Check your WiFi or Mobile Internet!</h4>
<span class="shadow"></span></div>
</body>
</html>
<application
android:icon="@mipmap/ic_app"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_app_round"
android:supportsRtl="true"
android:configChanges="keyboardHidden|orientation|screenSize"
android:theme="@style/Theme.AppCompat.NoActionBar">
<activity
android:name=".isNetworkAvailable"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mWebView.loadUrl("file:///android_asset/error.html");
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
tools:context=".isNetworkAvailable">
<ImageView
android:id="@+id/imageView2"
android:layout_width="389dp"
android:layout_height="439dp"
android:contentDescription="no internet check your connection"
android:src="@raw/no"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="@+id/bu"
android:layout_width="335dp"
android:layout_height="80dp"
android:layout_below="@id/imageView2"
android:layout_marginTop="32dp"
android:contentDescription="Tap to retry"
android:src="@raw/r"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView2" />
</android.support.constraint.ConstraintLayout>
Étape 1. Ajoutez le référentiel JitPack à votre fichier de construction. Ajoutez-le dans votre build.gradle racine à la fin des référentiels:
EagleEyeObserver.setConnectivityListener(new OnChangeConnectivityListener() { @Override public void onChanged(boolean status) { Toast.makeText(MainActivity.this, "" + status, Toast.LENGTH_SHORT).show(); } });
Étape 2. Ajoutez la dépendance
XXX
À faire Activer EagleEye Si vous ne remplacez pas la classe Application, modifiez votre fichier manifeste pour définir android: name dans la balise comme suit:
public class MyApplication extends EagleEyeApplication { ... }
Si vous remplacez la classe Application, remplacez-la par étendez EagleEyeApplication (si possible) comme suit:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapp"> <application android:name="org.sumon.eagleeye.EagleEyeApplication" > ... </application> </manifest>
Dans votre activité / fragment, obtenez le statut ci-dessous
dependencies { implementation 'com.github.SumonHub:EagleEye:1.0.0' }
plus d'informations ici
https://stackoverflow.com/a/52718543/8968370
Découvrez cette réponse. Je l'ai testé avec succès et il prend également en charge les anciennes versions d'Android. Bien qu'il ne détecte pas si la connexion dispose d'un accès Internet ou non. Mais vous pouvez l'utiliser si vous souhaitez simplement détecter si votre appareil est connecté à un réseau cellulaire ou Wi-Fi.
J'ai même créé une bibliothèque simple en utilisant cela.
Récepteur de diffusion pour vérifier la connexion Internet
Copie possible de l ' événement Android pour le changement d'état de la connectivité Internet