我正在进行一个需要将文件上传到服务器的项目。要上传大文件,将花费很多时间。为了避免这种情况,我想到了从后台上传文件。为了从后台上传文件,我在该服务内部使用了服务,而我正在使用异步任务来上传文件,问题是上传开始时,如果删除该应用程序意味着终止该服务也将停止。如何解决这个问题。请在下面找到我到目前为止的代码片段
public class BackgroundService extends Service {
ProgressRequestBody.UploadCallbacks callbacks = new ProgressRequestBody.UploadCallbacks() {
@Override
public void onProgressUpdate(int percentage) {
Log.i("percentage", "" + percentage);
}
@Override
public void onError() {
}
@Override
public void onFinish(int finished) {
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String filePath = intent.getStringExtra("filePath");
final int studentId = intent.getIntExtra("studentId", 0);
int documentType = intent.getIntExtra("type", 0);
uplodeBackground uplodeBackground = new uplodeBackground();
uplodeBackground.execute(filePath, String.valueOf(documentType), String.valueOf(studentId));
return START_STICKY;
}
class uplodeBackground extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... strings) {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
File file = new File(strings[0]);
//RequestBody progressRequestBody = RequestBody.create(MediaType.parse("multipart/*"), file);
ProgressRequestBody progressRequestBody = new ProgressRequestBody(file, callbacks);
MultipartBody.Part[] part = new MultipartBody.Part[2];
part[0] = MultipartBody.Part.createFormData("file", file.getName(), progressRequestBody);
part[1] = MultipartBody.Part.createFormData("documentTypeId", strings[1]);
RequestBody mStudendId = RequestBody.create(MediaType.parse("text/plain"), /*String.valueOf(studentId)*/strings[2]);
Call<JsonObject> call = apiInterface.uploadFile(part, mStudendId);
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (response.isSuccessful()) {
if (response.body().get("status").getAsInt() == 200) {
Log.i("test", "Uploaded successfully..........");
}
}
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.i("test", "Failed successfully..........");
}
});
return null;
}
}
}
您在forground服务中调用您的AsyncTask类。只有在应用程序在后台运行时,forground服务才会被杀死。