2

In my project, the requirement is to click a button to upload some images to the server by make an API call. However, the tricky part is that we assume the user may be in a place where network is not available. So there should be a way that always check the network connectivity. Only if the network is available then execute that upload images intent service.

Could you tell me what should I use? RxJava? BroadcastReceiver or something else? What is the best practice to handle this issue?

Many thanks!!!

Yongji Li
  • 21
  • 2

2 Answers2

2

One of the best practice ways to handle this would be do dispatch the image uploading job using Android's JobScheduler API. The JobScheduler will allow you to set conditions that the job must meet before the job is dispatched, one of which is network connectivity conditions.

Also, if you're targeting a lower API level and JobScheduler isn't available, the GCMNetworkManager is also an option.

Submersed
  • 8,810
  • 2
  • 30
  • 38
  • To use a single api on different api versions, consider android-job library from evernote. https://github.com/evernote/android-job – karandeep singh Feb 15 '18 at 19:28
0

You can use ConnectivityManager class , with a simple alert dialogue , in order to make sure that user is having internet connection , for example:

private NetworkState mNetworkState;
        mNetworkState = new NetworkState(mContext);
            if (!mNetworkState.isConnected()) {
            /**
             If application is not connected to the internet , then
             display dialog message and finish.
             */
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            mContext);
            // set dialog message
            alertDialogBuilder
            .setMessage("This application needs internet connection.")
            .setCancelable(false).setPositiveButton("Got it!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
/**
  In my case i close the current activity , by calling finish() 
 */
MainActivity.this.finish();
    }
    });
    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();
    // show it
    alertDialog.show();
    } else {
    /**
     YOUR CODE GOES HERE :
     */
    }

and for Network State class will be :

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
// This class for accessing network state for our application
public class NetworkState {

private final ConnectivityManager mConnectivityManager;


public NetworkState(Context context) {
    mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}

public boolean isConnected() {
    NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnectedOrConnecting();
} }
Omar Beshary
  • 310
  • 4
  • 10