Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/219.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java I';我试图在android中使用JobIntentService上传多个文件_Java_Android_Android Studio_Intentservice_Jobintentservice - Fatal编程技术网

Java I';我试图在android中使用JobIntentService上传多个文件

Java I';我试图在android中使用JobIntentService上传多个文件,java,android,android-studio,intentservice,jobintentservice,Java,Android,Android Studio,Intentservice,Jobintentservice,我正在尝试使用android中的JobIntentService上载多个文件。文件似乎已上载,但我无法在进度栏中跟踪进度。在整个上传过程中,进度条保持在同一位置,即使上传完成后,进度条也不会消失。我试图修改我在中找到的一个实现,但毫无结果 下面是我的FileUploadService.java类:- public class FileUploadService extends JobIntentService { private static final String TAG = "F

我正在尝试使用android中的JobIntentService上载多个文件。文件似乎已上载,但我无法在进度栏中跟踪进度。在整个上传过程中,进度条保持在同一位置,即使上传完成后,进度条也不会消失。我试图修改我在中找到的一个实现,但毫无结果

下面是我的FileUploadService.java类:-

public class FileUploadService extends JobIntentService {

    private static final String TAG = "FileUploadService";
    private static final int JOB_ID = 102;
    NotificationHelper mNotificationHelper;
    Disposable mDisposable;
    public static final int NOTIFICATION_ID = 1;
    public static final int NOTIFICATION_RETRY_ID = 2;
    private ArrayList<String> imagePaths;
    private static String token,folderId;

    @Override
    public void onCreate() {
        super.onCreate();
        mNotificationHelper = new NotificationHelper(this);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        Log.d(TAG, "onHandleWork: ");
        imagePaths = intent.getStringArrayListExtra("mFilePath");
        if (imagePaths == null) {
            Log.e(TAG, "onHandleWork: Invalid file URI");
            return;
        }
        RetrofitFactory<BaseNetworkResponse> mRetrofitFactory = RetrofitFactory.getInstance();
        IRetrofitContract iRetrofitContract = mRetrofitFactory.getRetrofitContract(RetroUtils.APP_ENV);
        Flowable<Double>fileObservable = Flowable.create(new FlowableOnSubscribe<Double>() {
            @Override
            public void subscribe(FlowableEmitter<Double> e) throws Exception {
                iRetrofitContract.uploadImage(token,folderId,createMultipart(imagePaths,e)).blockingGet();
            }
        }, BackpressureStrategy.LATEST);

        mDisposable = fileObservable.subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Double>() {
                    @Override
                    public void accept(Double progress) throws Exception {
                        // call onProgress()
                        FileUploadService.this.onProgress(progress);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        // call onErrors() if error occurred during file upload
                        FileUploadService.this.onErrors(throwable);
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        // call onSuccess() while file upload successful
                        FileUploadService.this.onSuccess();
                    }
                });
    }

    private void onErrors(Throwable throwable) {
        /**
         * Error occurred in file uploading
         */
        Intent successIntent = new Intent("com.wave.ACTION_CLEAR_NOTIFICATION");
        successIntent.putExtra("notificationId", NOTIFICATION_ID);
        sendBroadcast(successIntent);


        PendingIntent resultPendingIntent = PendingIntent.getActivity(this,
                0 /* Request code */, new Intent(this, StartCameraAndProcessImageActivity.class),
                PendingIntent.FLAG_UPDATE_CURRENT);

        /**
         * Add retry action button in notification
         */
        Intent retryIntent = new Intent(this, RetryJobReceiver.class);
        retryIntent.putExtra("notificationId", NOTIFICATION_RETRY_ID);
        retryIntent.putExtra("mFilePath", imagePaths);
        retryIntent.setAction(ACTION_RETRY);

        /**
         * Add clear action button in notification
         */
        Intent clearIntent = new Intent(this, RetryJobReceiver.class);
        clearIntent.putExtra("notificationId", NOTIFICATION_RETRY_ID);
        clearIntent.putExtra("mFilePath", imagePaths);
        clearIntent.setAction(ACTION_CLEAR);

        PendingIntent retryPendingIntent = PendingIntent.getBroadcast(this, 0, retryIntent, 0);
        PendingIntent clearPendingIntent = PendingIntent.getBroadcast(this, 0, clearIntent, 0);
        NotificationCompat.Builder mBuilder = mNotificationHelper.getNotification(getString(R.string.error_upload_failed), getString(R.string.message_upload_failed), resultPendingIntent);
        // attached Retry action in notification
        mBuilder.addAction(android.R.drawable.ic_menu_revert, getString(R.string.btn_retry_not), retryPendingIntent);
        // attached Cancel action in notification
        mBuilder.addAction(android.R.drawable.ic_menu_revert, getString(R.string.btn_cancel_not), clearPendingIntent);
        // Notify notification
        mNotificationHelper.notify(NOTIFICATION_RETRY_ID, mBuilder);
    }

    /**
     * Send Broadcast to FileProgressReceiver with progress
     *
     * @param progress file uploading progress
     */
    private void onProgress(Double progress) {
        Intent progressIntent = new Intent(this, FileProgressReceiver.class);
        progressIntent.setAction("com.wave.ACTION_PROGRESS_NOTIFICATION");
        progressIntent.putExtra("notificationId", NOTIFICATION_ID);
        progressIntent.putExtra("progress", (int) (100 * progress));
        sendBroadcast(progressIntent);
    }

    private void onSuccess() {
        Intent successIntent = new Intent(this, FileProgressReceiver.class);
        successIntent.setAction("com.wave.ACTION_UPLOADED");
        successIntent.putExtra("notificationId", NOTIFICATION_ID);
        successIntent.putExtra("progress", 100);
        sendBroadcast(successIntent);
    }


    private List<MultipartBody.Part> createMultipart(ArrayList<String> imagePaths, FlowableEmitter<Double> e) {
        ArrayList<MultipartBody.Part> partArrayList = new ArrayList<>();
        for (int i=0;i<imagePaths.size();i++){
            File file = new File(imagePaths.get(i));
            partArrayList.add(MultipartBody.Part.createFormData("file[]",file.getName(),createCountingRequestBody(file,"image/*",e)));
        }
        return partArrayList;
    }

    private RequestBody createCountingRequestBody(File file, String mimeType, final FlowableEmitter<Double> emitter) {
        RequestBody requestBody = createRequestBodyFromFile(file, mimeType);
        return new CountingRequestBody(requestBody, new CountingRequestBody.Listener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength) {
                double progress = (1.0 * bytesWritten) / contentLength;
                emitter.onNext(progress);
            }
        });
    }

    private RequestBody createRequestBodyFromFile(File file, String mimeType) {
        return RequestBody.create(MediaType.parse(mimeType), file);
    }

    public static void enqueueWork(Context context, Intent intent, String t, String id) {
        enqueueWork(context, FileUploadService.class, JOB_ID, intent);
        token = t;
        folderId = id;
    }

    public static void enqueueWork(Context context, Intent intent) {
        enqueueWork(context, FileUploadService.class, JOB_ID, intent);
    }
}

RetryJobReceiver类:-

public class RetryJobReceiver extends BroadcastReceiver {

    public static final String ACTION_RETRY = "com.wave.ACTION_RETRY";
    public static final String ACTION_CLEAR = "com.wave.ACTION_CLEAR";
    NotificationHelper mNotificationHelper;

    @Override
    public void onReceive(Context context, Intent intent) {
        /**
         * Handle notification user actions
         */
        mNotificationHelper = new NotificationHelper(context);
        int notificationId = intent.getIntExtra("notificationId", 0);
        ArrayList<String> filePath = intent.getStringArrayListExtra("mFilePath");
        switch (Objects.requireNonNull(intent.getAction())) {
            case ACTION_RETRY:
                mNotificationHelper.cancelNotification(notificationId);
                Intent mIntent = new Intent(context, FileUploadService.class);
                mIntent.putExtra("mFilePath", filePath);
                FileUploadService.enqueueWork(context, mIntent);
                break;
            case ACTION_CLEAR:
                mNotificationHelper.cancelNotification(notificationId);
                break;
            default:
                break;
        }
    }
}
公共类RetryJobReceiver扩展了BroadcastReceiver{
公共静态最终字符串ACTION\u RETRY=“com.wave.ACTION\u RETRY”;
公共静态最终字符串ACTION\u CLEAR=“com.wave.ACTION\u CLEAR”;
通知助手通知助手;
@凌驾
公共void onReceive(上下文、意图){
/**
*处理通知用户操作
*/
mNotificationHelper=新的NotificationHelper(上下文);
int notificationId=intent.getIntExtra(“notificationId”,0);
ArrayList filePath=intent.getStringArrayListExtra(“mFilePath”);
开关(Objects.requirennull(intent.getAction())){
案例操作\u重试:
mNotificationHelper.cancelNotification(notificationId);
Intent minent=newintent(上下文,FileUploadService.class);
putExtra(“mFilePath”,filePath);
FileUploadService.enqueueWork(上下文,minent);
打破
案件行动明确:
mNotificationHelper.cancelNotification(notificationId);
打破
违约:
打破
}
}
}
NotificationHelper类:-

public class NotificationHelper extends ContextWrapper {
    private NotificationManager manager;
    public static final String WAVE_CHANNEL = "default";


    public NotificationHelper(Context mContext) {
        super(mContext);
        NotificationChannel mChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(WAVE_CHANNEL,
                    getString(R.string.noti_channel_default), NotificationManager.IMPORTANCE_DEFAULT);

            mChannel.setLightColor(Color.GREEN);
            mChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            getManager().createNotificationChannel(mChannel);
        }
    }

    public NotificationCompat.Builder getNotification(String title, String body, int progress) {
        NotificationCompat.Builder mBuilder;
        mBuilder = new NotificationCompat.Builder(getApplicationContext(), WAVE_CHANNEL);
        mBuilder.setSmallIcon(getSmallIcon());
        mBuilder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent));
        mBuilder.setContentTitle(title)
                .setContentText(body)
                .setOngoing(true)
                //.setContentIntent(resultPendingIntent)
                .setDefaults(NotificationCompat.DEFAULT_ALL)
                .setPriority(NotificationCompat.PRIORITY_HIGH);
        mBuilder.setVibrate(new long[]{0L});
        mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        mBuilder.setProgress(100, progress, false);
        if (progress == 100) {
            mBuilder.setProgress(0, 0, false);
            mBuilder.setContentText(body);
        }
        return mBuilder;
    }


    public NotificationCompat.Builder getNotification(String title, String body, PendingIntent resultPendingIntent) {
        NotificationCompat.Builder mBuilder;
        mBuilder = new NotificationCompat.Builder(getApplicationContext(), WAVE_CHANNEL);
        mBuilder.setSmallIcon(getSmallIcon());
        mBuilder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent));
        mBuilder.setContentTitle(title)
                .setContentText(body)
                .setContentIntent(resultPendingIntent)
                .setDefaults(NotificationCompat.DEFAULT_ALL)
                .setPriority(NotificationCompat.PRIORITY_HIGH);
        mBuilder.setVibrate(new long[]{0L});
        mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

        return mBuilder;
    }

    /**
     * Send a notification.
     *
     * @param id           The ID of the notification
     * @param notification The notification object
     */
    public void notify(int id, NotificationCompat.Builder notification) {
        getManager().notify(id, notification.build());
    }

    /**
     * Get the small icon for this app
     *
     * @return The small icon resource id
     */
    private int getSmallIcon() {
        return android.R.drawable.stat_notify_sync;
    }

    /**
     * Get the notification manager.
     * <p>
     * Utility method as this helper works with it a lot.
     *
     * @return The system service NotificationManager
     */
    private NotificationManager getManager() {
        if (manager == null) {
            manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return manager;
    }

    public void cancelNotification(int notificationId) {
        getManager().cancel(notificationId);
    }
}
公共类NotificationHelper扩展ContextWrapper{
私人通知经理;
公共静态最终字符串WAVE_CHANNEL=“default”;
公共NotificationHelper(上下文mContext){
超级(mContext);
NotificationChannel mChannel=null;
if(android.os.Build.VERSION.SDK\u INT>=android.os.Build.VERSION\u code.O){
mChannel=新通知频道(WAVE_频道,
getString(R.string.noti\u channel\u default)、NotificationManager.IMPORTANCE\u default);
mcchannel.setLightColor(Color.GREEN);
mcchannel.setLockscreenVisibility(Notification.VISIBILITY\u PRIVATE);
getManager().createNotificationChannel(MCChannel);
}
}
public NotificationCompat.Builder getNotification(字符串标题、字符串正文、整数进度){
通知建筑商和造船商;
mBuilder=new NotificationCompat.Builder(getApplicationContext(),WAVE_通道);
setSmallIcon(getSmallIcon());
setColor(ContextCompat.getColor(getApplicationContext(),R.color.colorAccent));
mBuilder.setContentTitle(标题)
.setContentText(正文)
.正在进行(正确)
//.setContentIntent(结果结束内容)
.setDefaults(NotificationCompat.DEFAULT\u ALL)
.setPriority(通知兼容优先级高);
mBuilder.setVibrate(新长[]{0L});
mBuilder.setVisibility(通知兼容性VISIBILITY\u PUBLIC);
mBuilder.setProgress(100,progress,false);
如果(进度==100){
mBuilder.setProgress(0,0,false);
mBuilder.setContentText(正文);
}
归还垃圾桶;
}
public NotificationCompat.Builder getNotification(字符串标题、字符串正文、PendingEvent ResultPendingEvent){
通知建筑商和造船商;
mBuilder=new NotificationCompat.Builder(getApplicationContext(),WAVE_通道);
setSmallIcon(getSmallIcon());
setColor(ContextCompat.getColor(getApplicationContext(),R.color.colorAccent));
mBuilder.setContentTitle(标题)
.setContentText(正文)
.setContentIntent(结果结束内容)
.setDefaults(NotificationCompat.DEFAULT\u ALL)
.setPriority(通知兼容优先级高);
mBuilder.setVibrate(新长[]{0L});
mBuilder.setVisibility(通知兼容性VISIBILITY\u PUBLIC);
归还垃圾桶;
}
/**
*发送通知。
*
*@param id通知的id
*@param通知通知对象
*/
public void notify(int-id,NotificationCompat.Builder通知){
getManager().notify(id,notification.build());
}
/**
*获取此应用程序的小图标
*
*@返回小图标资源id
*/
私有int getSmallIcon(){
返回android.R.drawable.stat\u notify\u sync;
}
/**
*获取通知管理器。
*
*这个助手经常使用实用方法。
*
*@返回系统服务通知管理器
*/
私有通知管理器getManager(){
if(manager==null){
manager=(NotificationManager)getSystemService(Context.NOTIFICATION\u服务);
}
退货经理;
}
公共作废取消通知(int notificationId){
getManager().cancel(notificationId);
}
}
我的API:-

@Multipart
    @POST("/uploadImage")
    Single<BaseNetworkResponse> uploadImage(@Header("Authorization") String token, @Header("fileId") String fileId, @Part List<MultipartBody.Part> file);

@Multipart
@POST(“/uploadImage”)
单个上载映像(@Header(“Authorization”)字符串标记、@Header(“fileId”)字符串fileId、@Part List文件);
@Multipart
    @POST("/uploadImage")
    Single<BaseNetworkResponse> uploadImage(@Header("Authorization") String token, @Header("fileId") String fileId, @Part List<MultipartBody.Part> file);