Check internet connection in background

2020-07-24 06:11发布

I need to check for internet connection in background.... i am saving some data in my database and whenever i get internet connection, it should upload the data on my server... i need a background service which will check for internet connection continuously even if i close my App, i tried few methods but they all work only if i open my app... Currently i am checking the internet connection like this

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

NOTE I don't want a method which will not work after i close my app... Just like whatsapp when we close the app,We still get text messages

标签: android
7条回答
ゆ 、 Hurt°
2楼-- · 2020-07-24 06:33

Code check internet access by using timer, I have made a service for that First time I have posted on stack.... so sorry in advance because i am not able to post it in good format

    private Handler mHandler = new Handler();
    private Timer mTimer = null;
    long notify_interval = 1000;
    public static String str_receiver = "pravin.service.receiver";
    Intent intent;
    DatabaseHandler dh=new DatabaseHandler(this);
    public CheckInternet(){

    }
    @Override
    public void onCreate()
    {
        mTimer = new Timer();
        mTimer.schedule(new TimerTaskToGetInternetStatus(), 5, notify_interval);
        intent = new Intent(str_receiver);
    }
    private class TimerTaskToGetInternetStatus extends TimerTask {
        @Override
        public void run() {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    icConnected();
                }
            });

        }
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onStart(Intent intent,int startid)
    {


    }
    public boolean icConnected()
    {
        Log.d("Called " , "INTERNET");
        ConnectivityManager connec =
                (ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);

        // Check for network connections
        if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
                Log.d("INTERNET","TRUE");
                dh.getIssues();
                return true;
            // if connected with internet

            //makeText(this, " Connected ", LENGTH_LONG).show();
        } else if (
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {
                Log.d("INTERNET","FALSE");
                return false;
            //makeText(this, " Not Connected ", LENGTH_LONG).show();
        }
        return false;
    }
}
查看更多
一纸荒年 Trace。
3楼-- · 2020-07-24 06:36

I know it's too late to answer your question but still, this is a perfectly working solution.

We can easily do it by using a Service and a Broadcast Receiver simultaneously to get the output as you wish. This will work always i.e when app is running, app is minimized or when app is even removed from minimized apps.

  1. Manifest Code :

    <application
    ...
    <service android:name=".MyService" />
    </application>
    
  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();
    }
    }
    
  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();
    }
    
    }
    
  4. Your Activity Code

    startService(new Intent(getBaseContext(), MyService.class));
    
查看更多
够拽才男人
4楼-- · 2020-07-24 06:46

If you need to check Internet in Background even App is killed then must implement sticky service. Which will stick in background and will do uploading work for you. Create a DB or any other persistence storage in which you can save your data and maintian their status.

For E.g.- If data is uploaded then mark its status as true or remove it from DB and on next time get data whose status is not true or not sent to server yet.

查看更多
ら.Afraid
5楼-- · 2020-07-24 06:49
public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}

use this method anywhere

if (!isNetworkAvailable(this)) {

   } else {}
查看更多
对你真心纯属浪费
6楼-- · 2020-07-24 06:55
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();
    }
   }
 }

Android manifest

<?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>
查看更多
萌系小妹纸
7楼-- · 2020-07-24 06:59

Create a BroadcastReceiver to listen internet connectivity

    public class InternetConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        boolean isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting();

        if (networkChangedListener != null) {
            networkChangedListener.onNetworkConnectionChanged(isConnected);
        }
    }

    public static boolean isInternetConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) CustomApplication.getInstance()
                .getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        return networkInfo != null && networkInfo.isConnectedOrConnecting();
    }
}

Then configure receiver in Android Manifest

   <application

    .............>

     <receiver android:name=".BroadcastReceiver.InternetConnectivityReceiver" />

     .............

   </application>

Then check internet connection in your Activity

    if (!InternetConnectivityReceiver.isInternetConnected()) {
    Toast.makeText(teacher_homePage.this,"No Internet Connection",Toast.LENGTH_SHORT).show();
} else if (InternetConnectivityReceiver.isInternetConnected()) {
     Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
}
查看更多
登录 后发表回答