I want to take an user Screenshot, I used this code. I was take 3 permission, READ_EXTERNAL_STORE,WRITE_EXTERNAL_STORE, and READ_EXTERNAL_STORAGE. Problem not fix. It show open failed: EPERM (Operation not permitted)
public void tackeAndSaveScreenShot(Activity mActivity) {
View MainView = mActivity.getWindow().getDecorView();
MainView.setDrawingCacheEnabled(true);
MainView.buildDrawingCache();
Bitmap MainBitmap = MainView.getDrawingCache();
Rect frame = new Rect();
mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
//to remove statusBar from the taken sc
int statusBarHeight = frame.top;
//using screen size to create bitmap
int width = mActivity.getWindowManager().getDefaultDisplay().getWidth();
int height = mActivity.getWindowManager().getDefaultDisplay().getHeight();
Bitmap OutBitmap = Bitmap.createBitmap(MainBitmap, 0, statusBarHeight, width, height - statusBarHeight);
MainView.destroyDrawingCache();
try {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
//you can also using current time to generate name
String name="YourName";
File file = new File(path, name + ".png");
fOut = new FileOutputStream(file);
OutBitmap.compress(Bitmap.CompressFormat.PNG, 1000, fOut);
fOut.flush();
fOut.close();
//this line will add the saved picture to gallery
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
When I check on my Logcat. they show the problem is in
fOut = new FileOutputStream(file);
I get permission properly.
private void userPermission2(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.MANAGE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_CODE1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE && grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
userPermission2();
}else {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
}
I tried many why but don'work. Every time is the same problem.
The log is.
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10351; state: ENABLED
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/YourName.png: open failed: EPERM (Operation not permitted)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:492)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:236)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
W/System.err: at com.example.myapplication.MainActivity.tackeAndSaveScreenShot(MainActivity.java:93)
W/System.err: at com.example.myapplication.MainActivity$1.onClick(MainActivity.java:64)
W/System.err: at android.view.View.performClick(View.java:7570)
W/System.err: at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
W/System.err: at android.view.View.performClickInternal(View.java:7525)
W/System.err: at android.view.View.access$3900(View.java:836)
W/System.err: at android.view.View$PerformClick.run(View.java:28680)
W/System.err: at android.os.Handler.handleCallback(Handler.java:938)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:254)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8243)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006)
W/System.err: Caused by: android.system.ErrnoException: open failed: EPERM (Operation not permitted)
W/System.err: at libcore.io.Linux.open(Native Method)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:8125)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:478)
W/System.err: ... 16 more
String path = Environment.getExternalStorageDirectory().toString();
Change to:
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
And for Android 10 devices add android:legacyExternalStorage="true" to application tag in manifest file.
For Android 13+ devices you do not need any permission.
Related
this is manifest file :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:requestLegacyExternalStorage="true"
android:allowBackup="true"
...
</manifest>
i used tedpermission.
Text file named by date (ex:2020_10_23.txt)
from external storage(ex:storage/emulated/0/myDiary/2020_10_23.txt)
for i/o operation.
here core code in mainactivity :
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
Toast.makeText(MainActivity.this, "Permission granted", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
Toast.makeText(MainActivity.this, "Permission denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
}
};
#RequiresApi(api = Build.VERSION_CODES.R)
#Override
public void onCreate(Bundle savedInstanceState) {
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setDeniedMessage("External Storage READ/WRITE Denied")
.setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
.check();
...
final String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
final File myDir = new File(sdPath + "/myDiary");
string fileName = Integer.toString(year) + "_"
+ Integer.toString(monthOfYear + 1) + "_"
+ Integer.toString(dayOfMonth) + ".txt";
...
btnWrite.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
public void onClick(View v) {
try {
//openFileoutput Methods does not allow path delimiters.
File current_file = new File(myDir + "/" + fileName);
if (!current_file.getParentFile().exists()) {
if (!current_file.getParentFile().mkdirs()) {
Toast.makeText(getApplicationContext(),
"Failed to create folder : " + myDir, Toast.LENGTH_SHORT).show();
}
}
if (!current_file.exists()) {
if (!current_file.createNewFile()) {
Toast.makeText(getApplicationContext(),
"Failed to create file : " + myDir + "/" + fileName, Toast.LENGTH_SHORT).show();
}
}
FileOutputStream outFs = new FileOutputStream(new File(String.valueOf(current_file)));
String str = edtDiary.getText().toString();
outFs.write(str.getBytes());
outFs.close();
Toast.makeText(getApplicationContext(),
fileName + " is saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Failed to save file : " + myDir + "/" + fileName, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
...
//read text file from external storage
String readDiary(String fName) {
String diaryStr = null;
FileInputStream inFs;
try {
inFs = new FileInputStream(new File(fName));
byte[] txt = new byte[500];
inFs.read(txt);
inFs.close();
diaryStr = (new String(txt)).trim();
btnWrite.setText("modify");
} catch (IOException e) {
edtDiary.setHint("no existing diary");
btnWrite.setText("new save");
}
return diaryStr;
}
Android version: 11
App permissions :
and this is logcat:
2020-10-23 15:40:00.986 6178-6178/com.cookandroid.project8_1 W/System.err: java.io.IOException: No such file or directory
2020-10-23 15:40:00.986 6178-6178/com.cookandroid.project8_1 W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
2020-10-23 15:40:00.986 6178-6178/com.cookandroid.project8_1 W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
2020-10-23 15:40:00.986 6178-6178/com.cookandroid.project8_1 W/System.err: at java.io.File.createNewFile(File.java:1008)
2020-10-23 15:40:00.986 6178-6178/com.cookandroid.project8_1 W/System.err: at com.cookandroid.project8_1.MainActivity$3.onClick(MainActivity.java:102)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err: at android.view.View.performClick(View.java:7448)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err: at android.view.View.performClickInternal(View.java:7425)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err: at android.view.View.access$3600(View.java:810)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err: at android.view.View$PerformClick.run(View.java:28305)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err: at android.os.Handler.handleCallback(Handler.java:938)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err: at android.os.Looper.loop(Looper.java:223)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7656)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
it cannot create folder 'myDiary' on storage/emulated/0
I tried everything I could. why cannot create folder,file even i given external storage I/O Permissions?
On Android 11 you have no access to the root of external storage.
You cannot create files or folders in /storage/emulated/0.
But.. you can write to the usual public folders on /storage/emulated/0 like
Download, Documents, DCIM, Pictures, Alarms, a.s.o.
Look which folders there are already on your device and you can mostly use them for read and or write operations.
Use this
public class Folder
{
private final File appDataFolder;
public Folder()
{
File file = Environment.getExternalStorageDirectory();
appDataFolder = new File(file, "AppDataFolder");
if (!appDataFolder.exists()) appDataFolder.mkdir();
}
public String getMainFolder()
{
return appDataFolder.getAbsolutePath();
}
public void deleteMainFolder()
{
if (appDataFolder.isDirectory())
{
String[] children = appDataFolder.list();
for (String child : children)
{
new File(appDataFolder, child).delete();
}
}
new Folder();
}
public void createNewFolder(String folderName)
{
File file = new File(appDataFolder, folderName);
if (!file.exists()) file.mkdir();
}
public void createChildFolder(String parentName, String childName)
{
String path = appDataFolder.getAbsolutePath() + File.separator + parentName;
File parent = new File(path);
File file = new File(parent, childName);
if (!file.exists()) file.mkdir();
}
}
and in activity
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
new Folder().createNewFolder("myDiary");
Toast.makeText(MainActivity.this, "Permission granted", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
Toast.makeText(MainActivity.this, "Permission denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
}
};
So, I have to get GPS data from file MetaData. "No problem", I said, "This will only take an hour or two". Six hour later, here I am searching through all Android Documentation and Stack exchange questions I can yet I still cant get it to work.
My Code is straight forward:
I am using a ACTION_PICK to select a video (ACTION_OPEN_DOCUMENT Doesn't work either).
I Have already requested the following permissions and added to the Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
Below is code from the button listener
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK , MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
//intent.setType("video/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
startActivityForResult(Intent.createChooser(intent,"Select A Video"),REQUEST_VIDEO_CONTENT);
}
});
And From the OnActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent vIntent) {
super.onActivityResult(requestCode, resultCode, vIntent);
if ((requestCode == REQUEST_VIDEO_CAPTURE || requestCode == REQUEST_VIDEO_CONTENT) && resultCode == RESULT_OK) {
//Attempt to get Content Data
vIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
vIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
Uri vUri = vIntent.getData();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
vUri = MediaStore.setRequireOriginal(vUri);
}
try {
InputStream vIS = getContentResolver().openInputStream(vUri);
ExifInterface vExif = new ExifInterface(vIS);
} catch (SecurityException | IOException e) {
e.printStackTrace();
}
And finally, the lovely SecurityException:
W/System.err: java.lang.SecurityException: Permission Denial: reading com.google.android.apps.photos.contentprovider.impl.MediaContentProvider uri content://com.google.android.apps.photos.contentprovider/0/2/content%3A%2F%2Fmedia%2Fexternal%2Fvideo%2Fmedia%2F198668/ORIGINAL/NONE/video%2Fmp4/328149382?requireOriginal=1 from pid=6190, uid=10146 requires the provider be exported, or grantUriPermission()
W/System.err: at android.os.Parcel.createException(Parcel.java:2071)
at android.os.Parcel.readException(Parcel.java:2039)
W/System.err: at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:188)
at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:151)
W/System.err: at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:705)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1710)
W/System.err: at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1526)
W/System.err: at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:1345)
at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:1293)
W/System.err: at com.equinox.openeyes.VideoSubmission.onActivityResult(VideoSubmission.java:117)
at android.app.Activity.dispatchActivityResult(Activity.java:8147)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4883)
W/System.err: at android.app.ActivityThread.handleSendResult(ActivityThread.java:4931)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
W/System.err: at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2022)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:235)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
I get that the Error is saying the provider needs to be exported, or grantUriPermission which sounds like an easy fix, except I cannot find a way to implement what they ask. All the places I have looked have suggested adding flags.. as you can see it didnt work.
Please Help :-(
i am getting the following error when i try to debug the app, app is running without a crash but unable to load another location on map,
W/System.err: org.json.JSONException: Index 0 out of range [0..0)
W/System.err: at org.json.JSONArray.get(JSONArray.java:295)
at org.json.JSONArray.getJSONObject(JSONArray.java:523)
W/System.err: at praneeth.dev.androidpolorserver.TrackingOrder$1.onResponse(TrackingOrder.java:138)
W/System.err: at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:82)
at retrofit2.-
W/System.err: at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
W/System.err: at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7682)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
W/System.err: Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
W/System.err: at java.util.ArrayList.get(ArrayList.java:437)
at org.json.JSONArray.get(JSONArray.java:289)
... 11 more
this is my onResponse code,
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
String lat = ((JSONArray)jsonObject.get("results"))
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location")
.get("lat").toString();
String lng = ((JSONArray)jsonObject.get("results"))
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location")
.get("lng").toString();
LatLng orderLocation = new LatLng(Double.parseDouble(lat),Double.parseDouble(lng));
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.foodagent);
bitmap = Common.scaledBitmap(bitmap,70,70);
MarkerOptions marker = new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.title("Order of "+Common.currentRequest.getPhone())
.position(orderLocation);
mMap.addMarker(marker);
mService.getDirections(yourLocation.latitude+","+yourLocation.longitude,
orderLocation.latitude+","+orderLocation.longitude,"API_CODE")
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
new ParseTask().execute(response.body().toString());
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
call to toString(), is also redundant, can any one help me solve this. i am stuck at this for days
I know there are a few of these on SO already but none of them really were able to help my issue, but when I am running the code and start recording audio and then press my stop button it always fails because it is in the wrong state. I am not sure how I would go about fixing my states for this.
Here is my MainActivity.java code:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.IOException;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class MainActivity extends AppCompatActivity {
Button buttonStartRecording, buttonStopRecording, buttonPlayLastRecordAudio,
buttonStopPlayingRecording;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder;
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer;
AudioManager audioManager;
boolean isAudioPlayInSameDevice = true;
// AudioRouter audioRouter;
RadioGroup mRadioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStartRecording = (Button) findViewById(R.id.start_recording);
buttonStopRecording = (Button) findViewById(R.id.stop_rec);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.play_last_rec);
buttonStopPlayingRecording = (Button) findViewById(R.id.stop_playing_btn);
// mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
buttonStopRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
buttonStartRecording.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View view) {
// Check audio permission
if (checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "AudioRecording.3gp";
// Start Media recorder
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStartRecording.setEnabled(false);
buttonStopRecording.setEnabled(true);
Toast.makeText(MainActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStopRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
// Stop Media recorder
mediaRecorder.stop();
Toast.makeText(MainActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
int selectedId = 1;
if (selectedId == 1) {
isAudioPlayInSameDevice = true;
} else {
isAudioPlayInSameDevice = false;
}
// if you want to play audio on your Mobile speaker then set isAudioPlayInSameDevice true
// and if you want to play audio to connected device then set isAudioPlayInSameDevice false.
if (isAudioPlayInSameDevice) {
audioManager.setMode(audioManager.STREAM_MUSIC);
audioManager.setSpeakerphoneOn(true);
} else {
audioManager.setSpeakerphoneOn(false);
audioManager.setMode(audioManager.MODE_NORMAL);
}
audioManager.setBluetoothScoOn(false);
audioManager.stopBluetoothSco();
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
// Start media player
System.out.println("Recorded Audio Path-" + AudioSavePathInDevice);
mediaPlayer.setDataSource(AudioSavePathInDevice);
if (isAudioPlayInSameDevice) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if (mediaPlayer != null) {
// Stop Media Player
mediaPlayer.stop();
mediaPlayer.release();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
MediaRecorderReady();
}
}
}
});
}
private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
System.out.println("ANDROID Audio SCO state: " + state);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
/*
* Now the connection has been established to the bluetooth device.
* Record audio or whatever (on another thread).With AudioRecord you can record with an object created like this:
* new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
* AudioFormat.ENCODING_PCM_16BIT, audioBufferSize);
*
* After finishing, don't forget to unregister this receiver and
* to stop the bluetooth connection with am.stopBluetoothSco();
*/
}
}
};
#RequiresApi(api = Build.VERSION_CODES.O)
public void MediaRecorderReady() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_2_TS);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(mBluetoothScoReceiver, intentFilter);
audioManager = (AudioManager) getApplicationContext().getSystemService(getApplicationContext().AUDIO_SERVICE);
// Start Bluetooth SCO.
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(true);
audioManager.startBluetoothSco();
// Stop Speaker.
audioManager.setSpeakerphoneOn(false);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBluetoothScoReceiver);
// Stop Bluetooth SCO.
audioManager.stopBluetoothSco();
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(false);
// Start Speaker.
audioManager.setSpeakerphoneOn(true);
}
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
// if (StoragePermission && RecordPermission) {
// Toast.makeText(BluetoothAudioRecorder.this, "Permission Granted",
// Toast.LENGTH_LONG).show();
// } else {
// Toast.makeText(BluetoothAudioRecorder.this,"Permission Denied",Toast.LENGTH_LONG).show();
// }
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}
And then my logcat of when the error occurs:
2019-11-24 11:26:54.440 29627-29683/com.example.esense_application E/libc: Access denied finding property "vendor.gralloc.disable_ahardware_buffer"
2019-11-24 11:26:54.435 29627-29627/com.example.esense_application W/RenderThread: type=1400 audit(0.0:17779): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=24699 scontext=u:r:untrusted_app:s0:c7,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
2019-11-24 11:26:54.487 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:26:54.487 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 2
2019-11-24 11:26:54.868 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:26:57.769 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: java.io.FileNotFoundException: /storage/emulated/0/AudioRecording.3gp: open failed: EACCES (Permission denied)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at libcore.io.IoBridge.open(IoBridge.java:496)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:289)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:152)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.media.MediaRecorder.prepare(MediaRecorder.java:1046)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at com.example.esense_application.MainActivity$1.onClick(MainActivity.java:67)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.performClick(View.java:7140)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.performClickInternal(View.java:7117)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.access$3500(View.java:801)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View$PerformClick.run(View.java:27351)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.os.Handler.handleCallback(Handler.java:883)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.os.Handler.dispatchMessage(Handler.java:100)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.os.Looper.loop(Looper.java:214)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7356)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.Linux.open(Native Method)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7255)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.IoBridge.open(IoBridge.java:482)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: ... 15 more
2019-11-24 11:27:03.528 29627-29627/com.example.esense_application E/MediaRecorder: stop called in an invalid state: 4
2019-11-24 11:27:03.528 29627-29627/com.example.esense_application D/AndroidRuntime: Shutting down VM
2019-11-24 11:27:03.529 29627-29627/com.example.esense_application E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.esense_application, PID: 29627
java.lang.IllegalStateException
at android.media.MediaRecorder.stop(Native Method)
at com.example.esense_application.MainActivity$2.onClick(MainActivity.java:98)
at android.view.View.performClick(View.java:7140)
at android.view.View.performClickInternal(View.java:7117)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27351)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2019-11-24 11:27:03.540 29627-29627/com.example.esense_application I/Process: Sending signal. PID: 29627 SIG: 9
Your MediaRecorder is throwing when you try to stop() it because it has never entered the "recording" state. In fact, it never even entered the "prepared" state, because your call to prepare() did not complete successfully.
SOLUTION
Do not allow a call to start() until the prepare() call has returned (without throwing).
Do not allow a call to stop() until the start() call has returned (without throwing).
Make sure you have chosen a valid location for your output file. Try using getExternalFilesDir( null ) instead of Environment.getExternalStorageDirectory(). The bad file path is the reason your prepare() call is currently failing with an EACCESS.
As you can see, swallowing exceptions without addressing their root cause (i.e., just doing a e.printStackTrace() and carrying on), can rapidly lead to problems -- even in rough code used for learning/experimentation. If you are going to add an exception handler, it is better to provide real error handling -- and always make sure you understand why an exception is being thrown.
I am using the following code to write an onPostExecute process to file from my FileWriter.class, it was working fine but am updating my application and I have to use the Environment.getExternalStorageDirectory().getPath(); instead of this, i tried following. I know doing something slightly wrong. Any Help or direction would be helpful.
Thanks.
public class FileWriter {
public void appendData( String text) {
try {
File myFile = new File("/sdcard/latencyOP.csv");
// myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
if (myFile.createNewFile()) {
myOutWriter.append("TimeStamp,ExecutionTime,OperationType;");
}
myOutWriter.append(text);
myOutWriter.close();
fOut.close();
/**
* Toast.makeText(getBaseContext(),
* "Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
*/
} catch (Exception e) {
/**
* Toast.makeText(getBaseContext(), e.getMessage(),
* Toast.LENGTH_SHORT).show();
*/
}
}
}
EDIT
I forgot to add that I am attempting to do some background operations and publish results on the **FILE.csv** thread without having to manipulate threads.
UPDATED CODE #Leonardo Acevedo
try {
File myFile = new File(
Environment.getExternalStorageDirectory(),
"latencyOP.csv"
);
boolean needToCreateFile = !myFile.exists();
if (needToCreateFile) {
myFile.createNewFile();
}
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
// At this point your file is guaranteed to exist
if (needToCreateFile) {
myOutWriter.append("TimeStamp,ExecutionTime,OperationType;");
}
myOutWriter.append(text);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT
).show();
} catch (Exception e) {
e.printStackTrace();
displayExceptionMessage(e.getMessage());
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void displayExceptionMessage(String msg) {
//Toast.makeText(this, "Some Error Occured", Toast.LENGTH_SHORT).show();
}
ASYNCH TASK PROCESS
protected void onPreExecute(){ startTime = Calendar.getInstance().getTime().getTime();
}
protected void onPostExecute(Long result) {
endTime = Calendar.getInstance().getTime().getTime();
long timeDiff = endTime - startTime;
FileWriter fileWriter = new FileWriter();
String data = endTime + "," + timeDiff + "," + "Authentication" + ";";
fileWriter.appendData(data);
}
Is this wrong ?
03-14 20:42:52.062 17192-17192/com.demo.common.recordwritertest W/System.err: java.io.IOException: Permission denied
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at java.io.File.createNewFile(File.java:948)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.demo.common.recordwritertest.utils.FileWriter.appendData(FileWriter.java:25)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.demo.common.recordwritertest.com.demo.common.recordwritertest.asynctasks.AuthenticationAsyncTask.onPostExecute(AuthenticationAsyncTask.java:119)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.demo.common.recordwritertest.com.demo.common.recordwritertest.asynctasks.AuthenticationAsyncTask.onPostExecute(AuthenticationAsyncTask.java:27)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.AsyncTask.finish(AsyncTask.java:667)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.AsyncTask.-wrap1(AsyncTask.java)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.Looper.loop(Looper.java:154)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at java.lang.reflect.Method.invoke(Native Method)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)