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条回答
等我变得足够好
2楼-- · 2020-07-24 07:00

Probably there is some better way, but I've implemented this as a STICK_SERVICE as @Rahul suggested, and for avoiding killing the service I forced a fixed notification in status bar. I know this probably is not a good practice, however the client has asked to show "App is running..." in the status bar, so it's ok.

SyncService.class

public class SyncService extends IntentService {

    private static int FOREGROUND_ID = 1338;
    public Boolean isServiceRunning = false;
    Integer delay;
    private NotificationManager mgr;

    public SyncService() {
        super("SyncService");
    }

    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        performSync();
        startSyncThread();
        mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        final NotificationCompat.Builder builder = buildForeground();
        startForeground(1, builder.build());
        return START_STICKY;
    }

    public Boolean isWifiConnected() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifi.isConnected();
    }

    public void startSyncThread() {
        Handler handler = new Handler();
        delay = 1000;

        handler.postDelayed(new Runnable() {
            public void run() {
                performSync();
                handler.postDelayed(this, delay);
            }
        }, delay);
    }

    public void performSync() {
        if (isWifiConnected()) {
            Log.i("SyncService:", "Wifi connected, start syncing...");
            Sync sync = new Sync(this);
            sync.postPhotos();
            sync.postEvents();
            sync.getEvents();
            delay = 60000;
        } else {
            Log.i("SyncService:", "Wifi IS NOT connected, ABORT syncing...");
            delay = 1000;
        }
        Log.i("SyncService:", delay + "");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        WakefulReceiver.completeWakefulIntent(intent);
    }


    private NotificationCompat.Builder buildForeground() {
        Intent intent = new Intent(this, EventsActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        NotificationCompat.Builder b = new NotificationCompat.Builder(this);

        b.setContentTitle("Prime Share is running")
                .setSmallIcon(android.R.drawable.stat_notify_sync_noanim)
                .setOngoing(true)
                .setAutoCancel(false)
                .setPriority(Notification.PRIORITY_MAX)
                .setContentIntent(pendingIntent);

        return (b);

    }

}

And then in my first activity onCreate I call this:

context = this;
startSyncIntent = new Intent(this, SyncService.class);
startService(startSyncIntent);
查看更多
登录 后发表回答