gpt4 book ai didi

java - Android 帮助将图像保存到 Sd 卡并将广播发送到 MediaScanner

转载 作者:行者123 更新时间:2023-12-01 05:51:24 27 4
gpt4 key购买 nike

我在将图像从 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();
}
});
}
}

最佳答案

请使用MediaScannerConnection“刷新文件夹,以便图像出现在手机上的图库中”。

关于java - Android 帮助将图像保存到 Sd 卡并将广播发送到 MediaScanner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4565047/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com