我在将图片从r.drawable.image1保存到图片文件夹中的手机SD卡时出现问题,然后向MediaScanner发送广播以刷新文件夹,以便图片显示在手机的图库中
我相信解决方案与此相关
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
现在的问题是图像没有保存到SD并且我不知道将上面的代码放在媒体扫描程序的哪个位置,因为下面的代码在我过去3天摆弄它之后什么也没做。请帮忙......
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.net.Uri;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.Button;
import android.widget.Toast;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
public class MainScreen extends Activity
{
private Button btnDownload;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnDownload=(Button)findViewById(R.id.SaveButton1);
btnDownload.setOnClickListener(
new Button.OnClickListener() {
@Override
public void onClick(View v) {
String newPicture = saveToSDCard(R.drawable.image1, "image1.jpg");
startMediaScanner(newPicture);
}
}
);
}
private String saveToSDCard(int resourceID, String finalName)
{
StringBuffer createdFile = new StringBuffer();
Bitmap resourceImage = BitmapFactory.decodeResource(this.getResources(), resourceID);
File externalStorageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), finalName);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
resourceImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
byte b[] = bytes.toByteArray();
try
{
externalStorageFile.createNewFile();
OutputStream filoutputStream = new FileOutputStream(externalStorageFile);
filoutputStream.write(b);
filoutputStream.flush();
filoutputStream.close();
createdFile.append(externalStorageFile.getAbsolutePath());
}
catch (IOException e)
{
}
return createdFile.toString();
}
private void startMediaScanner(String fileName)
{
MediaScannerConnection.scanFile(this,
new String[] { fileName }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri)
{
Toast.makeText(MainScreen.this, "Media scan Completed", Toast.LENGTH_SHORT).show();
}
});
}
}
答案 0 :(得分:0)
请使用MediaScannerConnection
“刷新文件夹,以便图片显示在手机的图库中。”