在后台检查互联网连接

Hen*_*ekh 1 android

我需要在后台检查互联网连接....我在我的数据库中保存一些数据,每当我上网时,它应该在我的服务器上传数据...我需要一个后台服务,它将检查互联网连接即使我关闭我的应用程序,我尝试了几个方法,但他们都只有我打开我的应用程序... ...目前我正在检查这样的互联网连接

/checking internet connection

    ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {

        //we are connected to a network
        connected = true;

    }
    else
       //not connected to internet
        connected = false;

    if(connected) {
        //getting teacher data if INTERNET_STATE is true(if will be still true if connected to a wifi or network without internet)
        getOfflineSubjectData();
        getTeacherData();
    }
    else{
        getOfflineSubjectData();
        Toast.makeText(teacher_homePage.this,"no internet",Toast.LENGTH_SHORT).show();
    }
Run Code Online (Sandbox Code Playgroud)

注意 我不想要一个在关闭我的应用程序后无效的方法...就像我们关闭应用程序时的whatsapp一样,我们仍然会收到短信

ans*_*ile 5

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;

public class CheckConnectivity extends BroadcastReceiver{

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

    boolean isConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
    if(isConnected){
        Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
    }
   }
 }
Run Code Online (Sandbox Code Playgroud)

Android清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.connect.broadcast"
  android:versionCode="1"
  android:versionName="1.0" >

  <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8"/>

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

  <application
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name" >
       <receiver android:exported="false"
          android:name=".CheckConnectivity" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
     </receiver>
   </application>
</manifest>
Run Code Online (Sandbox Code Playgroud)


小智 5

我知道现在回答您的问题为时已晚,但这仍然是一个完美的解决方案。

我们可以通过同时使用服务和广播接收器来轻松获得所需的输出,从而轻松地做到这一点。这将始终有效,即当应用程序正在运行,应用程序最小化或什至从最小化应用程序中删除应用程序时。

  1. 清单代码:

    <application
    ...
    <service android:name=".MyService" />
    </application>
    
    Run Code Online (Sandbox Code Playgroud)
  2. MyService.java

    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.app.Service;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.IBinder;
    import android.support.annotation.Nullable;
    import android.support.v4.app.NotificationCompat;
    import android.util.Log;
    import android.widget.Toast;
    
    public class MyService extends Service {
    
    static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
    NotificationManager manager ;
    
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (CONNECTIVITY_CHANGE_ACTION.equals(action)) {
                    //check internet connection
                    if (!ConnectionHelper.isConnectedOrConnecting(context)) {
                        if (context != null) {
                            boolean show = false;
                            if (ConnectionHelper.lastNoConnectionTs == -1) {//first time
                                show = true;
                                ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
                            } else {
                                if (System.currentTimeMillis() - ConnectionHelper.lastNoConnectionTs > 1000) {
                                    show = true;
                                    ConnectionHelper.lastNoConnectionTs = System.currentTimeMillis();
                                }
                            }
    
                            if (show && ConnectionHelper.isOnline) {
                                ConnectionHelper.isOnline = false;
                                Log.i("NETWORK123","Connection lost");
                                //manager.cancelAll();
                            }
                        }
                    } else {
                        Log.i("NETWORK123","Connected");
                        showNotifications("APP" , "It is working");
                        // Perform your actions here
                        ConnectionHelper.isOnline = true;
                    }
                }
            }
        };
        registerReceiver(receiver,filter);
        return START_STICKY;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. ConnectionHelper.java

    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    
    public class ConnectionHelper {
    
    public static long lastNoConnectionTs = -1;
    public static boolean isOnline = true;
    
    public static boolean isConnected(Context context) {
    ConnectivityManager cm =(ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    
    return activeNetwork != null && activeNetwork.isConnected();
    }
    
    public static boolean isConnectedOrConnecting(Context context) {
    ConnectivityManager cm =(ConnectivityManager)         context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    
    return activeNetwork != null &&
    activeNetwork.isConnectedOrConnecting();
    }
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 您的活动代码

    startService(new Intent(getBaseContext(), MyService.class));
    
    Run Code Online (Sandbox Code Playgroud)