我有一个ListActivity,可以让用户选择要上传的照片
为了上传,我将照片放在名为PhotoList的静态ArrayList中
之后,我将启动服务以上传这些照片
现在,用户可以切换到其他活动来做其他事情
稍后,用户将返回到该ListActivity以检查上传状态。同样在这里,他们可以选择更多要上传的照片。
因此,我的PhotoList实际上是一种队列,但是它也是要在ListActivity中显示的数据。
我的问题是,当服务运行时,用户选择了更多照片时,我想将这些照片放入PhotoList中。
(我不想再次启动Service,因为该服务已经在运行...)
现在我被困在这里。
最佳答案
okey我将根据对您问题的理解为您提供解决方案:
您有一个包含照片的列表,并且希望用户有资格上传这些图像并以用户的状态(上载/上载/上载/失败)对其进行更新,并且您不想每次上载Service
。
一个简单的工作解决方案是使用IntnetService
,仅当分配了任务时我才会运行,并且在完成工作时会自动关闭,当然,在使用IntentService
时该工作将处于一个单独的线程中
step 1
使数据库表包含有关图像的数据
_id integer
_image_uri
_image_status :
_image_status
将保留以下值之一(1上载:finish_uploaded,2上载:服务正在上载图像,3-上载:用户可以上载图像4失败:上载失败可以重试)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中声明Service并享受。
关于android - 关于文件上传列表和服务/Activity 的设计模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14181240/