简体   繁体   English

从活动更新IntentService的数据

[英]Update data of IntentService from activity

I have an IntentService to upload images to server (source below). 我有一个IntentService可以将图像上传到服务器(下面的源)。 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. 您不能只是extend Service (不是IntentService ),将Activity绑定到Service,然后调用此Service的方法来上传图片。

In this way, your service will run until you call stopSelf() in the service or stopService() in your bounded activity. 这样,您的服务将一直运行,直到您在服务中的stopSelf()或有界活动中的stopService()为止。 Hence, you could use the same service to do multiple uploads. 因此,您可以使用同一服务进行多次上传。

Please let me know if this answer helped a bit... 请让我知道这个答案是否有帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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