I am using the built-in voice recorder in my Android App. Is there a way I can change the default location of recorded files? They are stored in the "Sound" folder in SD Card. I want to store them in a different folder. How do I do it, if that's even possible?
Below is a simple code for calling the built-in Android voice recorder App.
Button startRecording = (Button) findViewById(R.id.startBtn);
startRecording.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent recordIntent = new Intent(
MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(recordIntent, REQUEST_CODE_RECORD);
}
});
well you will have to allow the file to be recorded using where ever the default location and file name that are used and then move the file.
you could do something like this in your onActivityResult:
#Override protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_RECORD:
if (resultCode == Activity.RESULT_OK) {
// Sound recorder does not support EXTRA_OUTPUT
Uri uri = data.getData();
try {
String filePath = getAudioPathFromUri(uri);
copyFile(filePath);
getContentResolver().delete(uri, null, null);
(new File(filePath)).delete();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
private String getAudioPathFromUri(Uri uri) {
Cursor cursor = getContentResolver()
.query(uri, null, null, null, null);
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
return cursor.getString(index);
}
private void copyFile(String fileName) throws IOException {
Files.copy(new File(fileName),
new File(Environment.getExternalStorageDirectory(), fileName));
}
}
Related
I am trying to get the Path from an image to send it later to a server. The problem is when I try to get it, my code doesn't work (you will see there is an extra }. That is because the code from the OnCreate ends and then I worte the other functions):
enviar.setOnClickListener(new View.OnClickListener() {
String datos="";
//Bundle extras=getIntent().getExtras();
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
//Uri imagen=intent.getData();
//datos=imagen.getPath();
//mostrar.setText(datos);
}
});
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == this.RESULT_OK){
try {
final Uri imageUri = imageReturnedIntent.getData();
String path = getRealPathFromURI(imageUri);
mostrar.setText(path);
}
catch (Exception e) {
Log.e("Erroreeeee: ", e.getMessage());
}
}
break;
}
}
You have two problems.
The first one is that startActivityForResult() is not immediate. You do not have any results in the next statement.
So, you are welcome to call startActivityForResult(), as I do in this sample app:
private void get() {
Intent i=
new Intent()
.setType("image/png")
.setAction(Intent.ACTION_GET_CONTENT)
.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(i, REQUEST_GET);
}
Your results are delivered to onActivityResult():
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (resultCode==Activity.RESULT_OK) {
Uri image=resultData.getData();
// do something
}
}
Your second problem is that you are thinking that you are picking a file. You are not. You are picking a piece of content, using any activity that the user decides to have handle ACTION_GET_CONTENT. getPath() only has meaning if the scheme of the Uri is file, and that is rather unlikely. There is no reliable means of getting a filesystem path for an arbitrary Uri, for the simple reason that the Uri does not have to point to a file.
Ideally, your "upload to a server" logic can work with an InputStream. In that case, call openInputStream() on a ContentResolver to get an InputStream on the content identified by the Uri. If your "upload to a server" logic only works with files, use that InputStream to copy the content to some temporary file that you control (e.g., in getCacheDir()), then use that temporary file for your upload. Delete the temporary file when you are done with it.
I used Intent ACTION_GET_CONTENT to show recent files from phone memory. That includes images, pdf, google drive documents(pdf, xlsx) as shown in screenshot below. I want to get the name and full path so that I can upload the file to server. I/m getting the mime type correctly as of now.
public class MainActivity extends AppCompatActivity {
Button btn;
TextView txt;
private final static int EXTERNAL = 111;
private final static int ATTACH = 11;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn);
txt = (TextView)findViewById(R.id.txt);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
photoIntent();
} else {
if (shouldShowRequestPermissionRationale(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// showToast("Permission Required...");
}
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL);
}
} else {
photoIntent();
}
}
});
}
private void photoIntent() {
Intent intent = new Intent();
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath());
intent.setDataAndType(uri, "*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), ATTACH);
}
#Override
public void onRequestPermissionsResult(int requestcode, String[] permission, int[] grantRes){
if (requestcode == EXTERNAL) {
if (grantRes[0] == PackageManager.PERMISSION_GRANTED) {
photoIntent();
} else {
Toast.makeText(this, "Unable to Access Image", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ATTACH && resultCode == RESULT_OK){
Uri uri = data.getData();
System.out.println("sammy_sourceUri "+uri);
String mimeType = getContentResolver().getType(uri);
System.out.println("sammy_mimeType "+ mimeType);
}
}
}
I want to get the name and full path so that I can upload the file to server
There is no "full path", because there may not be a "file".
You are invoking ACTION_GET_CONTENT. This returns a Uri to some content. Where that content comes from is up to the developers of the ACTION_GET_CONTENT activity that the user chose. That could be:
An ordinary file on the filesystem that happens to be one that you could access
An ordinary file on the filesystem that resides somewhere that you cannot access, such as internal storage for the other app
A file that requires some sort of conversion for it to be useful, such as decryption
A BLOB column in a database
Content that is generated on the fly, the way this Web page is generated on the fly by the Stack Overflow servers
And so on
To use the content from the Uri, use a ContentResolver and openInputStream().
how to use this InputStream to upload to server API as file?
Either your chosen HTTP API supports an InputStream as the source of this content, or it does not. If it does, just use the InputStream directly. If not, use the InputStream to make a temporary copy of the content as a file that you can directly access (e.g., in getCacheDir()), upload that file, then delete the file when the upload is complete.
try this
public static ArrayList<String> getImagesFromCameraDir(Context context) {
Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ArrayList<String> filePaths = new ArrayList<>();
final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED};
Cursor mCursor = context.getContentResolver().query(mImageUri, columns, MediaStore.Images.Media.DATA + " like ? ", new String[]{"%/DCIM/%"}, null);
if (mCursor != null) {
mCursor.moveToFirst();
try {
int uploadImage = 0;
uploadImage = mCursor.getCount();
for (int index = 0; index < uploadImage; index++) {
mCursor.moveToPosition(index);
int idx = mCursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
filePaths.add(mCursor.getString(idx));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
mCursor.close();
}
}
return filePaths;
}
get real path from URI
public String getRealPathFromURI(Uri contentUri)
{
String[] proj = { MediaStore.Audio.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
FILENAME :
String filename = path.substring(path.lastIndexOf("/")+1);
I am creating an android mobile application in which user can upload his/her resume and which can be then sent to the server.
Resume can be in pdf form or word form.
How to browse for the pdf and word files, which type should be given to browse these files? like for images we have image.
Thanks.
Use this function:
private void getDocument()
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/msword,application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Only the system receives the ACTION_OPEN_DOCUMENT, so no need to test.
startActivityForResult(intent, REQUEST_CODE_DOC);
}
#Override
protected void onActivityResult(int req, int result, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(req, result, data);
if (result == RESULT_OK)
{
Uri fileuri = data.getData();
docFilePath = getFileNameByUri(this, fileuri);
}
}
// get file path
private String getFileNameByUri(Context context, Uri uri)
{
String filepath = "";//default fileName
//Uri filePathUri = uri;
File file;
if (uri.getScheme().toString().compareTo("content") == 0)
{
Cursor cursor = context.getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA, MediaStore.Images.Media.ORIENTATION }, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String mImagePath = cursor.getString(column_index);
cursor.close();
filepath = mImagePath;
}
else
if (uri.getScheme().compareTo("file") == 0)
{
try
{
file = new File(new URI(uri.toString()));
if (file.exists())
filepath = file.getAbsolutePath();
}
catch (URISyntaxException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
filepath = uri.getPath();
}
return filepath;
}
I hope this will help you.
I have an application which is running on desktop fine .There is one button on my desktop app in which it open the gallary select image.
But when I run that app on webview what will happen when I clcik that button .? will it open our mobile image gallary .?
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri in onActivityResult() like so:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath() method in my FileUtils.java is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
I have to following code to launch and the audio recorder on Android:
final Intent recordSoundIntent = new Intent
("android.provider.MediaStore.RECORD_SOUND");
String fileName = Environment.getExternalStorageDirectory() +
File.separator + UUID.randomUUID() + ".3gpp";
recordSoundIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new
File(fileName)));
startActivityForResult(Intent.createChooser(recordSoundIntent,
getString(R.string.record_sound_chooser)), INTENT_SOUND_RECORDING);
My problem is the following:
My filename (fileName) has no effect, the Uri returned from
data.getData() returns in my last test run: content://media/external/audio/media/41.
However, this file is created on my sdcard: recording34485.3gpp. If it
is not possible to set custom location upon creating sound it is the
location to this file I would like.
Was working on the same problem. Could not find a way to set location directly but found a work around solution of getting and renaming it.
Getting file name was dealt with here, file is then renamed using java.io.File.renameTo(). You'll need android.permission.WRITE_EXTERNAL_STORAGE in your manifest file for the rename to work.
Here is my test code example:
public static final int REQUEST_RECORD_SOUND = 7;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, REQUEST_RECORD_SOUND);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUEST_RECORD_SOUND){
String sourcePath = getRealPathFromURI(intent.getData());
File root = Environment.getExternalStorageDirectory();
String destPath = root.getPath() + File.separator + "newName.txt";
File sourceF = new File(sourcePath);
try {
sourceF.renameTo(new File(destPath));
} catch (Exception e) {
Toast.makeText(this, "Error:" + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
/**
* from:
* https://stackoverflow.com/questions/3401579/get-filename-and-path-from-uri-from-mediastore
*/
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}