I am having some trouble with saving an image from r.drawable.image1 to the phone's SD Card in a Pictures Folder, then sending a broadcast to the MediaScanner to refresh the folders so that the image appears in the gallery on the phone.
I beleive the solution is something to do with this
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
The problem now is the image does not save to sd and I do not know where to put the above code for the media scanner as the code below does nothing now after me fiddling with it for the last 3 days. Please Help...
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStrea开发者_如何转开发m;
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();
}
});
}
}
Please use MediaScannerConnection
"to refresh the folders so that the image appears in the gallery on the phone".
精彩评论