我设置拍照,保存,然后上传图片。我的问题是MediaScannerConnection在尝试上传图片之前没有完成。我需要一些不同类型的退货声明吗?我怎么能让它等待?
已修改为包含完整代码。
public void onClick(View v) {
if (v.getId() == R.id.capture_btn) {
String fileName = System.currentTimeMillis() + ".jpg";
String path1 = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ File.separator + "Photos App";
try {
path = new File(path1);
if (!path.exists()) {
path.mkdirs();
}
} catch (Exception e) {
Log.d("creating file error", e.toString());
}
photo = new File(path, fileName);
Log.d("main screen", "photo = " + photo);
Intent cameraintent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
cameraintent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
startActivityForResult(cameraintent,
CAMERA_IMAGE_CAPTURE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_IMAGE_CAPTURE
&& resultCode == Activity.RESULT_OK) {
scanMedia();
if(scanned){
new PostPicture().execute();
}
}
}
private File scanMedia() {
// TODO Auto-generated method stub
MediaScannerConnection.scanFile(MainScreen.this,
new String[] { photo.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
scanned = true;
}
});
return path;
}
class PostPicture extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
答案 0 :(得分:2)
答案是将异步任务放在runnable中。我发现我无法尝试在主UI线程之外加载异步任务。此外,下面的代码会让它等到它完成扫描。
private File scanMedia() {
// TODO Auto-generated method stub
MediaScannerConnection.scanFile(MainScreen.this,
new String[] { photo.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
fullPath = path;
scanned = true;
if(scanned){
new Thread()
{
public void run()
{
MainScreen.this.runOnUiThread(new Runnable()
{
public void run()
{
new PostPicture().execute();
}
});
}
}.start();
} else {
Log.e("Should scan","Didn't finish scanning");
}
}
});
return path;
}
答案 1 :(得分:0)
从您的代码中无法理解,我认为您需要添加其余内容。
但是,试试这个:
private File scanMedia() {
// TODO Auto-generated method stub
MediaScannerConnection.scanFile(MainScreen.this,
new String[] { photo.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
scanned = true;
if(scanned){
new PostPicture().execute();
} else {
Log.e("Should scan","Didn't finish scanning")
}
}
});
return path;
}
并删除
if(scanned){
new PostPicture().execute();