How to restrict other applications from accessing my images in android phone? - android

I don't want to root my phone.
There are some android apps that require permissions -
1. "modify or delete the contents of your SD card"
2. "read the contents of your SD card"
I want to use the app but I don't want it to read my personal images/data in the phone storage.
Is there any way to hide my images from those apps?
Will putting images to a zip folder work ?
Also, I actually don't have external SD card. All data is in phone's internal storage. So, are these permissions for internal storage also ?

Create a hidden folder you create a hidden folder by adding a . before folder name e.g the name folder will be like .name or create a .nomedia file in the folders you want not to be accessed by other application hence media scanner will not scan any folder with .nomedia you can do this by using this code:
public static String saveUserImageToSd_2(Bitmap mbmp, String mlocation, String mfilename) {
final Bitmap bmp = mbmp;
final String location = mlocation;
final String filename = mfilename;
/*--- this method will save your downloaded image to SD card ---*/
FileOutputStream fos = null;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
/*--- you can select your preferred CompressFormat and quality.
* I'm going to use JPEG and 100% quality ---*/
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
/*--- create a new folder on SD card ---*/
File createFolders = new File(Environment.getExternalStorageDirectory()
+ File.separator + location);
createFolders.mkdirs();
final String fileName = Environment.getExternalStorageDirectory()
+ File.separator + location + filename;
fileLocation = fileName;
System.err.println("fileLocation: 1"+fileName);
System.err.println("fileLocation: 2"+fileLocation);
fileExistance(fileName);
File file = new File(createFolders, filename);
File noMedia = new File(createFolders, ".nomedia");
try {
noMedia.createNewFile();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/*--- create a new FileOutputStream and write bytes to file ---*/
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
assert fos != null;
fos.write(bytes.toByteArray());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return fileLocation;
}
so this code will create a nomedia file in the directory you specified
or use this code to simply create a hidden folder:
make sure the location looks like ".myFoldername/djkvhsdfherkjghdf/" where myFoldername begins with a .
public static String createFolder(String location)
{
File createFolders = new File(Environment.getExternalStorageDirectory()
+ File.separator + location);
createFolders.mkdirs();
return createFolders.getAbsolutePath();
}
public static String creatFile(String location, String filename)
{
String filePath = Environment.getExternalStorageDirectory()
+ File.separator + location + filename;
return filePath;
}
public static File createFolderAndFIle(String location, String filename)
{
File createFolders = new File(Environment.getExternalStorageDirectory()
+ File.separator + location);
createFolders.mkdirs();
final String fileName = Environment.getExternalStorageDirectory()
+ File.separator + location + filename;
fileExistance(fileName);
File file = new File(createFolders, filename);
File noMedia = new File(createFolders, Constant.NOMEDIA);
try {
noMedia.createNewFile();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
//checking if file exists
private static void fileExistance(String filePath) {
File file = new File(filePath);
if (file.exists()) {
deleteFile(filePath);
}
}

Related

Trying to create folder in internal storage but code working only in oppo handset not in other brand handsets

Trying to create folder in internal storage but code working only in oppo handset not in other brand handsets like samsung,mi etc
public void createPDF()
{
TextView dttt = (TextView)findViewById(R.id.dttt);
String da = dttt.getText().toString();
final Cursor cursor = db.getDateWise(da);
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CollactionApp"+ "/PDF";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
int i = 1;
File file = new File(dir, "Datewise" + da + ".pdf" );
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
}
// Check premissions in Manifest and at run time
String root_sd = Environment.getExternalStorageDirectory().toString();
createExDirectory("CollactionApp", root_sd);
String path = root_sd + "/CollactionApp"+ "/PDF.pdf";
File f = new File(path);
try {
if (!f.exists()) {
f.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
public static String createExDirectory(String folderName, String pathToExternalStorage) {
String returnPath = "";
boolean success = false;
Boolean isSDPresent = Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED);
if (isSDPresent) {
// SD-card is present
File appDirectory = new File(pathToExternalStorage + "/" + folderName);
if (appDirectory.exists()) {
success = true;
} else {
success = appDirectory.mkdirs();
}
if (success) {
returnPath = appDirectory.getAbsolutePath();
} else {
}
}
return returnPath;
}
The path you are using points to the external storage. I've had an app before which have been working for long on all devices until recently, so I had to do a refactor on it, so I don't use the getExternalStorageDirectory() anymore.
I now use the Context's getFilesDir(), on which I didn't get the same issue again.
You would want your path to be something like below to use internal storage.
File internalDir = getContext().getFilesDir();
File myFolder = new File(internalDir, "/CollactionApp"+ "/PDF");
String path = myFolder.getAbsolutePath;

How to save files(publically) on internal storage even if the external storage is available in android?

How to save files(publically) on internal storage even if the external storage is available in android?
I want to save files on the internal storage root path even if the external storage is mounted.
suppose have a text file and save to local storage
public boolean saveFile(Context context, String myTextString){
try {
FileOutputStream fos = context.openFileOutput(getFilename(),Context.MODE_PRIVATE);
Writer out = new OutputStreamWriter(fos);
out.write(myTextString);
out.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath);
if (!file.exists()) {
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".txt");
}
Hope this helps..

Write a string to a file

I want to write something to a file. I found this code:
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
The code seems very logical, but I can't find the config.txt file in my phone.
How can I retrieve that file which includes the string?
Not having specified a path, your file will be saved in your app space (/data/data/your.app.name/).
Therefore, you better save your file onto an external storage (which is not necessarily the SD card, it can be the default storage).
You might want to dig into the subject, by reading the official docs
In synthesis:
Add this permission to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It includes the READ permission, so no need to specify it too.
Save the file in a location you specify (this is taken from my live cod, so I'm sure it works):
public void writeToFile(String data)
{
// Get the directory for the user's public pictures directory.
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
Environment.DIRECTORY_DCIM + "/YourFolder/"
);
// Make sure the path directory exists.
if(!path.exists())
{
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "config.txt");
// Save your stream, don't forget to flush() it before closing it.
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
[EDIT] OK Try like this (different path - a folder on the external storage):
String path =
Environment.getExternalStorageDirectory() + File.separator + "yourFolder";
// Create the folder.
File folder = new File(path);
folder.mkdirs();
// Create the file.
File file = new File(folder, "config.txt");
Write one text file simplified:
private void writeToFile(String content) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file);
writer.append(content);
writer.flush();
writer.close();
} catch (IOException e) {
}
}
This Method takes File name & data String as Input and dumps them in a folder on SD card.
You can change Name of the folder if you want.
The return type is Boolean depending upon Success or failure of the FileOperation.
Important Note: Try to do it in Async Task as FIle IO make cause ANR on Main Thread.
public boolean writeToFile(String dataToWrite, String fileName) {
String directoryPath =
Environment.getExternalStorageDirectory()
+ File.separator
+ "LOGS"
+ File.separator;
Log.d(TAG, "Dumping " + fileName +" At : "+directoryPath);
// Create the fileDirectory.
File fileDirectory = new File(directoryPath);
// Make sure the directoryPath directory exists.
if (!fileDirectory.exists()) {
// Make it, if it doesn't exist
if (fileDirectory.mkdirs()) {
// Created DIR
Log.i(TAG, "Log Directory Created Trying to Dump Logs");
} else {
// FAILED
Log.e(TAG, "Error: Failed to Create Log Directory");
return false;
}
} else {
Log.i(TAG, "Log Directory Exist Trying to Dump Logs");
}
try {
// Create FIle Objec which I need to write
File fileToWrite = new File(directoryPath, fileName + ".txt");
// ry to create FIle on card
if (fileToWrite.createNewFile()) {
//Create a stream to file path
FileOutputStream outPutStream = new FileOutputStream(fileToWrite);
//Create Writer to write STream to file Path
OutputStreamWriter outPutStreamWriter = new OutputStreamWriter(outPutStream);
// Stream Byte Data to the file
outPutStreamWriter.append(dataToWrite);
//Close Writer
outPutStreamWriter.close();
//Clear Stream
outPutStream.flush();
//Terminate STream
outPutStream.close();
return true;
} else {
Log.e(TAG, "Error: Failed to Create Log File");
return false;
}
} catch (IOException e) {
Log.e("Exception", "Error: File write failed: " + e.toString());
e.fillInStackTrace();
return false;
}
}
You can write complete data in logData in File
The File will be create in Downlaods Directory
This is only for Api 28 and lower .
This will not work on Api 29 and higer
#TargetApi(Build.VERSION_CODES.P)
public static File createPrivateFile(String logData) {
String fileName = "/Abc.txt";
File directory = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/");
directory.mkdir();
File file = new File(directory + fileName);
FileOutputStream fos = null;
try {
if (file.exists()) {
file.delete();
}
file = new File(getAppDir() + fileName);
file.createNewFile();
fos = new FileOutputStream(file);
fos.write(logData.getBytes());
fos.flush();
fos.close();
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

Android app Image is not saving in specified Sd Card folder after Crop, Showing empty folder

I am capturing the image using camera in my android app.
then Cropping the image.
after Cropping saving the image in specified folder.
Folder is creating, But image is not saving in the folder.(Its Empty)
Help me to resolve it
code I have used,
link referred
if (extras != null) {
Bitmap photooutput = extras.getParcelable("data");
// Camera Output
if (pick == 1) {
viewImage.setImageBitmap(photooutput);
String path = Environment.getExternalStorageDirectory().toString();
File m_imgDirectory = new File(path + "/WallPaper/");
if (!m_imgDirectory.exists()) m_imgDirectory.mkdir();
FileOutputStream m_fOut = null;
File directory2 = new File(path);
directory2.delete();
String m_fileid = System.currentTimeMillis() + "";
directory2 = new File(path, "/Wall/" + m_fileid + ".png");
try
{
if (!directory2.exists()) directory2.createNewFile();
m_fOut = new FileOutputStream(directory2);
Bitmap m_bitmap = photooutput.copy(Bitmap.Config.ARGB_8888, true);
m_bitmap.compress(Bitmap.CompressFormat.PNG, 100, m_fOut);
m_fOut.flush();
m_fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
directory2.getAbsolutePath(), directory2.getName(), directory2.getName());
}
catch (Exception p_e)
{
}
}
}
When using Android KitKat and above, it is impossible for an app to save a file onto the SDCard.
Check this Thread
UPDATE
Save an image to internal storage:
public static Uri saveImage(Bitmap bmp) {
Uri uri = null;
try {
String name = System.currentTimeMillis() + ".jpg";
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(getImagesDir() + File.separator + name);
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bitmapToByteArray(bmp));
// remember close de FileOutput
fo.close();
uri = Uri.parse("file://" + f.getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return uri;
}
public static String getImagesDir() {
String rootDir = Environment.getExternalStorageDirectory().toString();
rootDir = rootDir + "/MyApp/Media/Images";
// Create directory if not existed
File dir = new File(rootDir);
if (!dir.exists()) {
dir.mkdir();
}
return dir.getPath();
}
public static byte[] bitmapToByteArray(Bitmap bmp) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
UPDATE 2: missing code added
Add the following permissions to your AndroidManifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

android save images to internal storage

I'm having problems implementing this code Saving and Reading Bitmaps/Images from Internal memory in Android
to save and retrieve the image that I want, here is my code:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory, + name + "profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
and to retrieve(I don't know if I'm doing wrong)
#Override
protected void onResume()
{
super.onResume();
try {
File f = new File("imageDir/" + rowID, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
image = (ImageView) findViewById(R.id.imageView2);
image.setImageBitmap(b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and nothing happens so what should I change??
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
I think Faibo's answer should be accepted, as the code example is correct, well written and should solve your specific problem, without a hitch.
In case his solution doesn't meet your needs, I want to suggest an alternative approach.
It's very simple to store image data as a blob in a SQLite DB and retrieve as a byte array. Encoding and decoding takes just a few lines of code (for each), works like a charm and is surprisingly efficient.
I'll provide a code example upon request.
Good luck!
Note that you are saving the pick as name + profile.jpg under imageDir directory and you're trying to retrieve as profile.jpg under imageDir/[rowID] directory check that.
I got it working!
First make sure that your app has the storage permission enabled:
Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!
Permissions in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
So, if you want to create your own directory in your File Storage you can use somethibng like:
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
refreshGallery(outFile);
Else, if you want to create a sub directory in your default device DCIM folder and then want to view your image in a separate folder in gallery:
FileOutputStream fos= null;
File file = getDisc();
if(!file.exists() && !file.mkdirs()) {
//Toast.makeText(this, "Can't create directory to store image", Toast.LENGTH_LONG).show();
//return;
print("file not created");
return;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmsshhmmss");
String date = simpleDateFormat.format(new Date());
String name = "FileName"+date+".jpg";
String file_name = file.getAbsolutePath()+"/"+name;
File new_file = new File(file_name);
print("new_file created");
try {
fos= new FileOutputStream(new_file);
Bitmap bitmap = viewToBitmap(iv, iv.getWidth(), iv.getHeight() );
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Toast.makeText(this, "Save success", Toast.LENGTH_LONG).show();
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
print("FNF");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
refreshGallery(new_file);
Helper functions:
public void refreshGallery(File file){
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
}
private File getDisc(){
String t= getCurrentDateAndTime();
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(file, "ImageDemo");
}
private String getCurrentDateAndTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formattedDate = df.format(c.getTime());
return formattedDate;
public static Bitmap viewToBitmap(View view, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Hope this helps!

Categories

Resources