我正在处理的应用程序允许用户共享图像,它使用ACTION_SEND Intent完成。一切正常,除非处理意图的活动在实际共享文件之前返回。
例如。如果我使用Google云端硬盘分享图片,我的应用会在实际发送文件之前收到onActivityResult事件。由于在处理该事件的代码中我删除了临时文件,因此将文件上载到Drive会失败。有没有办法共享文件而不保存?或者也许某种方式可以知道它何时被实际发送,那么它可以被删除呢?
以下是我的应用中的一些相关代码。
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
// ...
public static final int REQUEST_SHARE_ACTION = 1;
private File temporaryShareFile;
// ...
protected void share (Bitmap bitmap) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
if(saveTemporaryFile(bitmap)) {
shareIntent.putExtra(
Intent.EXTRA_STREAM,
Uri.fromFile(this.temporaryShareFile)
);
startActivityForResult(
Intent.createChooser(shareIntent, "Share Image"),
REQUEST_SHARE_ACTION
);
} else {
Toast.makeText(
this,
R.string.file_save_fail_message,
Toast.LENGTH_LONG
).show();
}
}
protected boolean saveTemporaryFile (Bitmap bitmap) {
if(createTemporaryFile()) {
return writeTemporaryFile(bitmap);
}
return false;
}
protected boolean createTemporaryFile() {
this.temporaryShareFile = createFile("tmp_", ".jpg");
if (this.temporaryShareFile != null) {
return true;
} else {
return false;
}
}
protected File createFile(String prefix, String suffix) {
File outputDirectory = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
),
getResources().getString(R.string.app_name)
);
if(!outputDirectory.isDirectory()) {
if (!outputDirectory.mkdirs()) {
}
}
File file = null;
try {
file = File.createTempFile(
prefix,
suffix,
outputDirectory
);
return file;
} catch (IOException ioex) {
return null;
}
}
protected boolean writeTemporaryFile(Bitmap bitmap) {
return writeImageFile(
this.temporaryShareFile,
bitmap,
Bitmap.CompressFormat.JPEG,
100
);
}
protected boolean writeImageFile(
File file,
Bitmap bitmap,
Bitmap.CompressFormat format,
int quality
) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(format, quality, fileOutputStream);
fileOutputStream.close();
return true;
} catch (Exception e) {
//error writing file
Log.e("writeImageFile",e.getMessage());
return false;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_SHARE_ACTION) {
temporaryShareFile.delete();
}
}