简体   繁体   中英

Update data of IntentService from activity

I have an IntentService to upload images to server (source below). While upload is in progress, user might select more images to upload. Right now it spawns another service. How can I add data to same running service or spawn new service if its not running

public class UploadService extends IntentService {

    public static final String TAG = UploadService.class.getSimpleName();

    public static final String ACTION_UPLOAD = UploadService.class.getName() + ".UPLOAD";
    public static final String EXTRA_RESOURCE_ID = "resource_id";
    public static final String EXTRA_RESOURCE_NAME = "resource_name";
    public static final String EXTRA_IMAGES = "images";

    private static final int CONCURRRENT_UPLOAD_COUNT = 3;
    private static final int UPLOAD_STATUS_PENDING = 0;
    private static final int UPLOAD_STATUS_UPLOADING = 1;
    private static final int UPLOAD_STATUS_UPLOADED = 2;
    private static final int UPLOAD_STATUS_FAILED = 3;
    private static final int UPLOAD_STATUS_TERMINATED = 4;

    private ArrayList<DiskImage> mImages = new ArrayList<>();
    private ArrayMap<DiskImage, Integer> mStatusMap = new ArrayMap<>();
    private OkHttpClient mOkHttpClient = new OkHttpClient();

    public UploadService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent.getAction().equals(ACTION_UPLOAD)) {
            String resId = intent.getStringExtra(EXTRA_RESOURCE_ID);
            String resName = intent.getStringExtra(EXTRA_RESOURCE_NAME);
            ArrayList<DiskImage> images = intent.getParcelableArrayListExtra(EXTRA_IMAGES);
            for (DiskImage image : images) {
                image.mUploadId = resId;
                image.mUploadResName = resName;
            }
            mImages.addAll(images);
            upload(); // start the upload
            updateNotification();
        }
    }

    private int getUploadedImageCount() {
        int count = 0;
        for (int i = 0; i < mImages.size(); i++)
            if (getStatus(mImages.get(i)) == UPLOAD_STATUS_UPLOADED)
                count++;
        return count;
    }

    private void updateNotification() {
        UploadNotification.notify(UploadService.this, mImages.size(), getUploadedImageCount());
    }

    private void upload() {
        final DiskImage image = getImageToUpload();
        if (image != null) {
            // show notification
            MediaType mediaType = MediaType.parse(image.mimeType);
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("resource_id", image.mUploadId)
                    .addFormDataPart("resource_name", image.mUploadResName)
                    .addFormDataPart("image", getName(image.path),
                            RequestBody.create(mediaType, new File(image.path)))
                    .build();
            Request request = new Request.Builder()
                    .url(getUploadUrl())
                    .post(requestBody)
                    .build();
            mStatusMap.put(image, UPLOAD_STATUS_UPLOADING);
//            Log.i(TAG, "Uploading image " + getName(image.path));
            mOkHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    mStatusMap.put(image, UPLOAD_STATUS_FAILED);
                    // add failed image in end
                    mImages.remove(image);
                    mImages.add(image);
//                    Log.i(TAG, "Upload failed " + getName(image.path));
                    upload();
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
//                    Log.i(TAG, "Uploaded image " + getName(image.path) + " Response: " + response.body().string());
                    mStatusMap.put(image, UPLOAD_STATUS_UPLOADED);
                    upload(); // upload next image
                    updateNotification();
                }
            });
        }
    }

    private String getName(String path) {
        return path.substring(path.lastIndexOf(File.separator) + 1, path.length());
    }

    private DiskImage getImageToUpload() {
        for (int i = 0; i < mImages.size(); i++)
            if (getStatus(mImages.get(i)) == UPLOAD_STATUS_PENDING)
                return mImages.get(i);
        return null;
    }

    private String getUploadUrl() {
        return String.format(Constants.ALBUM_IMAGE_UPLOAD_URL, Preferences.getToken(this));
    }

    private int getStatus(DiskImage image) {
        if (mStatusMap.get(image) == null)
            return UPLOAD_STATUS_PENDING;
        return mStatusMap.get(image);
    }

}

Couldn't you just extend Service (not IntentService ), bind your Activity to the Service and then call a method of this Service, that does the upload of the picture.

In this way, your service will run until you call stopSelf() in the service or stopService() in your bounded activity. Hence, you could use the same service to do multiple uploads.

Please let me know if this answer helped a bit...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM