好的,我会根据我对您的问题的理解尝试为您提供解决方案:您有一个包含照片的列表,并且您希望用户有资格上传这些图像并将其更新为用户状态(已上传/上传/上传/失败)并且您不想在Service
每次上传时都开始。
一个简单的工作解决方案是使用IntnetService
i 只有在分配了任务时才会运行,并且在完成工作时自动关闭,当然在使用时工作将在一个单独的线程中IntentService
step 1
使数据库表包含有关图像的数据
_id integer
_image_uri
_image_status :
_image_status
将保留这些值之一(1-uploaded:finish_uploaded,2-uploading:服务正在上传图片,3-upload:用户可以上传图片4-failed:上传失败您可以重试)
step2
现在正在UploadIntentService
尝试将图像上传到服务器以及上传成功或上传时发生错误时更新数据库
public class UploadIntentService extends IntentService {
private static final String TAG = UploadIntentService.class.getSimpleName();
private static final int STATUS_UPLOAD = 0x01; //can be uploaded
public static final int STATUS_FAILED_TO_UPLOAD = 0x02; // tried to upload but failed
public static final int STATUS_UPLOADING = 0x03; // self explanied
public static final int STATUS_SUCCESSFULLY_UPLOADED = 0x04; // the image uploaded to server
public UploadIntentService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
int status = intent.getIntExtra("status", -1);
String imageUri = intent.getStringExtra("image_path");
long imageDatabaseid = intent.getLongExtra("image_db_address",-1);
if(status != STATUS_SUCCESSFULLY_UPLOADED && status != STATUS_UPLOADING){
try{
//update _image_status column with value of STATUS_UPLOADING with the image_id = imageDatabaseid;
//upload code
//successfully uploaded
//update _image_status column with value of STATUS_SUCCESSFULLY_UPLOADED with the image_id = imageDatabaseid;
}catch(Exception ex){
ex.printStackTrace();
//update _image_status column with value of STATUS_FAILED_TO_UPLOAD with the image_id = imageDatabaseid;
}
}
}
}
……
step3
如果ListActivity
您想上传任何图片,请使用此代码
Intent intent = new Intent(context, UploadIntentService.class);
Bundle uploadExtras = new Bundle(3);
uploadExtras.putLong("image_db_address", PUT HERE THE IMAGE DATABASE ID );
uploadExtras.putInt("status", PUT HERE THE IMAGE STATUS );
uploadExtras.putString("image_path", PUT HERE THE IMAGE PATH IN FILE SYSTEM);
intent.putExtras(uploadExtras);
context.startService(intent);
....... 第4步
确保您在 manifest.xml 中声明了服务,并享受。