- 我有一个 ListActivity 让用户选择要上传的照片
- 对于上传,我会将照片放入名为 PhotoList 的静态 ArrayList 中
- 之后,我将启动一项服务来上传这些照片
- 现在,用户可以切换到另一个 Activity 来执行其他操作
- 稍后,用户将返回此 ListActivity 以检查上传状态。他们还可以在这里选择更多要上传的照片。
所以,我的PhotoList实际上是一种Queue,但它也是要在ListActivity中显示的数据。
我的问题是,当服务运行时,用户选择了更多照片,我想将这些照片放入照片列表中。 (我不想再次启动服务,因为服务已经在运行...)
现在我被困在这里了。
最佳答案
好吧,我会根据我对您问题的理解尝试为您提供解决方案:
您有一个包含照片的列表,并且希望用户有资格上传这些图像并更新其状态(已上传/正在上传/上传/失败),并且您不想启动服务
每次上传。
一个简单的工作解决方案是使用 IntnetService
仅当有任务分配给它时,我才会运行,并且在完成工作时会自动关闭,当然,在使用 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中声明了该服务,然后就可以使用了。
关于android - 关于文件上传列表和服务/Activity 的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14181240/