Reputation: 2087
I have an application which records and stores audio on the device. My main activity contains a bunch of buttons to other activities. These other activities are the ones that do the actual audio recording.
My main activity is set up as follows:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mSmallVowel;
private Button mSayCat;
private Button mCough;
private Button mSaySentence;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String sep = File.separator;
String newFolder = "AudioRecordingTest";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + sep + newFolder);
myNewFolder.mkdir();
mSmallVowel = (Button) findViewById(R.id.btnSmallVowel);
mSmallVowel.setOnClickListener(this);
mSayCat = (Button) findViewById(R.id.btnSayCat);
mSayCat.setOnClickListener(this);
mCough = (Button) findViewById(R.id.btnCough);
mCough.setOnClickListener(this);
mSaySentence = (Button) findViewById(R.id.btnSaySentence);
mSaySentence.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.btnSmallVowel:
Intent small_vowel_intent = new Intent(this, SmallVowel.class);
this.startActivity(small_vowel_intent);
break;
case R.id.btnSayCat:
Intent say_cat_intent = new Intent(this, SayCat.class);
this.startActivity(say_cat_intent);
break;
case R.id.btnCough:
Intent cough_intent = new Intent(this, Cough.class);
this.startActivity(cough_intent);
break;
case R.id.btnSaySentence:
Intent say_sentence_intent = new Intent(this, SaySentence.class);
this.startActivity(say_sentence_intent);
break;
}
}
}
And all the other activities look like the following:
public class SaySentence extends AppCompatActivity {
private MediaRecorder recorder;
private String OUTPUT_FILE;
private TextView mStatus;
private TextView mRecorded;
//folder initialization
private String sep = File.separator;
private String mChildFolder = "SaySentence";
private String mExtStorageDirectory = Environment.getExternalStorageDirectory().toString();
private File mChildFile = new File(mExtStorageDirectory + sep + "AudioRecordingTest" + sep + mChildFolder);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_say_sentence);
mChildFile.mkdir();
mStatus = (TextView) findViewById(R.id.txtStatus);
mRecorded = (TextView) findViewById(R.id.txtRecorded);
}
public void startSpeaking(View view) {
//clear text
mRecorded.setText("");
try {
beginRecording();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopSpeaking(View view) {
try {
stopRecording();
} catch (Exception e) {
e.printStackTrace();
}
}
private void beginRecording() {
ditchMediaRecorder();
//get number of files already in sub-folder and increment the audio filename accordingly
File[] filesInFolder = mChildFile.listFiles();
if (filesInFolder != null) {
int count = filesInFolder.length;
OUTPUT_FILE = mExtStorageDirectory + sep + "AudioRecordingTest" + sep + mChildFolder + sep + "saysentence" + (count+1) + ".3gpp";
}
else {
OUTPUT_FILE = mExtStorageDirectory + sep + "AudioRecordingTest" + sep + mChildFolder + sep + "saysentence0" + ".3gpp";
}
File outFile = new File(OUTPUT_FILE);
mStatus.setText("Recording");
if(outFile.exists()){
outFile.delete();
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(OUTPUT_FILE);
try {
recorder.prepare();
} catch (Exception e) {
e.printStackTrace();
}
recorder.start();
}
private void stopRecording() {
mStatus.setText("Recording Stopped");
mRecorded.setText("Audio file saved to: " + OUTPUT_FILE);
if(recorder != null){
recorder.stop();
}
}
private void ditchMediaRecorder() {
if(recorder != null) {
recorder.release();
}
}
}
Since in Android 6.0 permissions have to be asked at run time, I would like to make it so that the main activity requests all the permissions I require in my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.soufinrahimeen.audiorecordingtest">
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher_medical"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SmallVowel" />
<activity android:name=".SayCat" />
<activity android:name=".Cough" />
<activity android:name=".SaySentence"></activity>
</application>
</manifest>
I have looked at the official docs on Requesting Permissions at Run Time, however, the official tutorial makes it seem like I need to ask for permissions in the activities that actually record and save the audio.
I would like to make it so that the MainActivity requests all the required permissions, and once the user enables them, it allows them to use the rest of the application without any issue.
How can I achieve this?
Upvotes: 1
Views: 14139
Reputation: 9225
Add these lines to check mulitple permissions in your code:
public static final int MULTIPLE_PERMISSIONS = 100;
// function to check permissions
private void checkPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.RECORD_AUDIO) + ContextCompat
.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE))
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(getActivity(), Manifest.permission.RECORD_AUDIO) ||
ActivityCompat.shouldShowRequestPermissionRationale
(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(
new String[]{Manifest.permission
.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
MULTIPLE_PERMISSIONS);
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(
new String[]{Manifest.permission
.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
MULTIPLE_PERMISSIONS);
}
}
} else {
// put your function here
}
}
// Function to initiate after permissions are given by user
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case MULTIPLE_PERMISSIONS:
if (grantResults.length > 0) {
boolean recordPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean writeExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(recordPermission && writeExternalFile)
{
// put your function here
}
}
else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(
new String[]{Manifest.permission
.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
MULTIPLE_PERMISSIONS);
}
}
}
}
Upvotes: 4
Reputation: 3348
Try this,
private Context mContext=YourActivity.this;
private static final int REQUEST = 112;
if (Build.VERSION.SDK_INT >= 23)
{
String[] PERMISSIONS = {android.Manifest.permission.RECORD_AUDIO,android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (!hasPermissions(mContext, PERMISSIONS))
{
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
}
else
{
//do here
}
} else {
//do here
}
get Permissions Result
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do here
} else {
Toast.makeText(mContext, "The app was not allowed to permissions.", Toast.LENGTH_LONG).show();
}
}
}
}
check permissions for marshmallow
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
Manifest
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Upvotes: 1