2

I am developing an android application that can upload images one by one of a specific folder to the server from background without interrupting the UI. What I implemented is a intentService calls from the launcher activity with the runtime permissions to read the READ_EXTERNAL_STORAGE. I need to upload all the files in the folder and also need to upload new file that are created or moved to the folder. For that I created a file observer class, which I think is not working properly.

  public class DirectoryFileObserver extends FileObserver {
String aboslutePath = "";

public DirectoryFileObserver(String path) {
    super(path, FileObserver.ALL_EVENTS);
    aboslutePath = path;
    Log.i("watch path", path);
}

@Override
public void onEvent(int event, String path) {
    Log.i("FileObserver++", "File Created:" + path);
    File file = new File(aboslutePath + "/" + path);
    List<Skeem> mSkeemList = Skeem.find(Skeem.class, "file = ?", new String[]{file.getAbsolutePath()});
    if (mSkeemList.size() == 0) {
        Skeem mSkeem = new Skeem();
        mSkeem.setUsername(AppConstants.UserEmail);
        mSkeem.setFolderName(aboslutePath);
        mSkeem.setFile(file.getAbsolutePath());
        uploadService uploadService = new uploadService();
        uploadService.upload(mSkeem);

    }

    switch (event) {
        case FileObserver.ALL_EVENTS:
            Log.d("All", "Path" + path);
            break;
        case FileObserver.CREATE:
            Log.d("Create", "Path" + path);
            break;
    }


}
 }

Also created a broad cast receiver as follows to resume file upload when the net connection is retained

public class InternetConnector_Receiver extends BroadcastReceiver {
    public InternetConnector_Receiver() {
    }

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

        boolean isVisible = BaseApplication
                .isActivityVisible();// Check if
        // activity
        // is
        // visible
        // or not
        Log.i("Activity is Visible ", "Is activity visible : " + isVisible);

        // If it is visible then trigger the task else do nothing
        if (isVisible == true) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager
                    .getActiveNetworkInfo();

            // Check internet connection and accrding to state change the
            // text of activity by calling method
            if (networkInfo != null && networkInfo.isConnected()) {

                Intent serviceIntent = new Intent(context, uploadService.class);
                context.startService(serviceIntent);

            } else {

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
}

and in manifest

   <receiver
        android:name=".InternetConnector_Receiver"
        android:enabled="true">
        <intent-filter>
            <!-- Intent filters for broadcast receiver -->
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
    </receiver>

I add all the files to the database with a status false.

    File[] files = directory.listFiles();
                        for (int n = 0; n < skeemList.size(); n++) {
                            Skeem skeem = skeemList.get(n);
                            for (int o = 0; o < files.length; o++) {
                                if (!(skeem.getFile().equalsIgnoreCase(files[o].getAbsolutePath()))) {
                                    if (!files[o].isDirectory()) {
                                        Skeem mSkeem = new Skeem();
                                        mSkeem.setFile(files[o].getAbsolutePath());
                                        mSkeem.setFolderName(directory.getName());
                                        mSkeem.setUsername(email);
                                        upload(mSkeem);
                                    } 
                                }
                            }
                        }

Then I starts uploading the files with status false and update table with status true. When I launch the application, the image upload starts successfully. But after some time it stops. Am I using correct Service to upload files from background? Is there any way to upload the contents of the folder? I have gone through so many sites and links. But I couldn't find the exact solution I needed. Please help me.

Cecil Paul
  • 595
  • 6
  • 27

2 Answers2

4

With the new Background Limitations for Service execution you need to be very cautious with background services. Instead of an IntentService I recommend you to use a JobIntentService as Google suggests. Pre-Oreo it acts as an IntentService, on (Post-)Oreo it uses Jobs to do background work. Remember to request WAKE_LOCK permission

Florian Hansen
  • 746
  • 7
  • 19
0

If you are open to use GitHub library -

https://github.com/gotev/android-upload-service 2.3K stars Apr 2020

enter image description here

" -Easily upload files (Multipart/Binary/FTP out of the box) in the background with progress indication notification

-upload files to a server with FTP, HTTP multipart/form-data or binary requests

-handle multiple concurrent uploads in the background, even if the device is idle (Doze mode)

-automatically retry failed uploads, with a configurable exponential backoff possibility to automatically delete uploaded files when the upload is successful

Apps and libraries powered by this library-

-JIRA Cloud

-Quora

...

"

zennni
  • 1,397
  • 15
  • 12