READ_EXTERNAL_STORAGE permission for Android - java

I'm trying to access media files (music) on the users device to play them; an easy "hello world"-music player app.
I've followed some tutorials and they basically give the same code. But it won't work; it keeps crashing and telling me:
error.....
Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=27696, uid=10059 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
....
Now, this is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="slimsimapps.troff" >
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
This is my Java-method:
public void initialize() {
ContentResolver contentResolver = getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = contentResolver.query(uri, null, null, null, null);
if (cursor == null) {
// query failed, handle error.
} else if (!cursor.moveToFirst()) {
// no media on the device
} else {
do {
addSongToXML(cursor);
} while (cursor.moveToNext());
}
}
I have tried:
To put this at different places in the manifest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE”/>
To add android:maxSdkVersion at Read external storage premission:
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="21" />
To put this in the manifest / application / activity-tag:
android:exported=“true”
To put grantUriPremission between uri and cursro in the javamethod:
grantUriPermission(null, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
To use this, it won't crash, but the cursor becomes null:
uri = MediaStore.Audio.Media.getContentUri("EXTERNAL_CONTENT_URI”);
To use INTERNAL content uri, this works as expected, but it only gives "OS-sounds" such as shutter-sound, low-battery-sound, button-click and such:
uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
Pleas help, this should not be a hard problem i know, but i feel like such a beginner!
I have read and tried (or considered them to be not applicable for my problem):
Android READ_EXTERNAL_STORAGE permission not working
Require permission only for older android versions: maxSdkVersion does not work?
Get filename and path from URI from mediastore
Android KitKat securityException when trying to read from MediaStore
Android: java.lang.SecurityException: Permission Denial: start Intent
Stack trace:
09-08 06:59:36.619 2009-2009/slimsimapps.troff D/AndroidRuntime﹕ Shutting down VM
--------- beginning of crash
09-08 06:59:36.619 2009-2009/slimsimapps.troff E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: slimsimapps.troff, PID: 2009
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.view.View$DeclaredOnClickListener.onClick(View.java:4452)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4447)
            at android.view.View.performClick(View.java:5198)
            at android.view.View$PerformClick.run(View.java:21147)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2009, uid=10059 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
at android.os.Parcel.readException(Parcel.java:1599)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
at android.content.ContentResolver.query(ContentResolver.java:491)
at android.content.ContentResolver.query(ContentResolver.java:434)
at slimsimapps.troff.MainActivity.initialize(MainActivity.java:106)
at slimsimapps.troff.MainActivity.InitializeExternal(MainActivity.java:80)
            at java.lang.reflect.Method.invoke(Native Method)
            at android.view.View$DeclaredOnClickListener.onClick(View.java:4447)
            at android.view.View.performClick(View.java:5198)
            at android.view.View$PerformClick.run(View.java:21147)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
--------- beginning of system

You have two solutions for your problem. The quick one is to lower targetApi to 22 (build.gradle file).
Second is to use new and wonderful ask-for-permission model:
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
Sniplet found here: https://developer.android.com/training/permissions/requesting.html
Solutions 2: If it does not work try this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSION);
return;
}
and then in callback
#Override
public void onRequestPermissionsResult(final int requestCode, #NonNull final String[] permissions, #NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
} else {
// User refused to grant permission.
}
}
}
that is from comments. thanks

You have to ask for the permission at run time:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSION);
dialog.dismiss();
return;
}
And in the callback below you can access the storage without a problem.
#Override
public void onRequestPermissionsResult(final int requestCode, #NonNull final String[] permissions, #NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
} else {
// User refused to grant permission.
}
}
}

Step1: add permission on android manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Step2: onCreate() method
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_MEDIA);
} else {
readDataExternal();
}
Step3: override onRequestPermissionsResult method to get callback
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_MEDIA:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
readDataExternal();
}
break;
default:
break;
}
}
Note: readDataExternal() is method to get data from external storage.
Thanks.

I also had a similar error log and here's what I did-
In onCreate method we request a Dialog Box for checking permissions
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
Method to check for the result
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted and now can proceed
mymethod(); //a sample method called
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
// add other cases for more permissions
}
}
The official documentation to Requesting Runtime Permissions

Has your problem been resolved? What is your target SDK? Try adding android;maxSDKVersion="21" to <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

In 2021 I am facing this issue
So I will solve this problem using
the manifest file I add one tag inside application:
<application
android:requestLegacyExternalStorage="true"
/>
NOTE: This only work until Android 10, see more information here

http://developer.android.com/reference/android/provider/MediaStore.Audio.AudioColumns.html
Try changing the line contentResolver.query
//change it to the columns you need
String[] columns = new String[]{MediaStore.Audio.AudioColumns.DATA};
Cursor cursor = contentResolver.query(uri, columns, null, null, null);
public static final String MEDIA_CONTENT_CONTROL
Not for use by third-party applications due to privacy of media consumption
http://developer.android.com/reference/android/Manifest.permission.html#MEDIA_CONTENT_CONTROL
try to remove the <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/> first and try again?

Please Check below code that using that You can find all Music Files from sdcard :
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animations);
getAllSongsFromSDCARD();
}
public void getAllSongsFromSDCARD() {
String[] STAR = { "*" };
Cursor cursor;
Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
cursor = managedQuery(allsongsuri, STAR, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String song_name = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
String album_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
int album_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
String artist_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
int artist_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
System.out.println("sonng name"+fullpath);
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
I have also added following line in the AndroidManifest.xml file as below:
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

In addition of all answers.
You can also specify the minsdk to apply with this annotation
#TargetApi(_apiLevel_)
I used this in order to accept this request even my minsdk is 18. What it does is that the method only runs when device targets "_apilevel_" and upper.
Here's my method:
#TargetApi(23)
void solicitarPermisos(){
if (ContextCompat.checkSelfPermission(this,permiso)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
1);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
}

Related

Application keep crashing

I am a beginner android app user. i am trying to make a BLE scanner based on a online example. however my app keep crashing and not working at all. can anyone please help me identify the problem?
I have looked into various online solutions. the example i am following is this:
https://github.com/kaviles/BLE_Tutorials
this is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ble_scanner">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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>
</application>
</manifest>
here is my MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
private final static String TAG = MainActivity.class.getSimpleName();
public static final int REQUEST_ENABLE_BT = 1;
private HashMap<String, BTLE_Device> mBTDevicesHashMap;
private ArrayList<BTLE_Device> mBTDevicesArrayList;
private ListAdapter_BTLE_Devices adapter;
private Button btn_Scan;
private BroadcastReceiver_BTState mBTStateUpdateReceiver;
private Scanner_BTLE mBTLeScanner;
private static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkLocationPermission();
if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
Utils.toast(getApplicationContext(),"BLE not supported");
finish();
}
mBTStateUpdateReceiver = new BroadcastReceiver_BTState(getApplicationContext());
mBTLeScanner = new Scanner_BTLE(this,7500,-75);
mBTDevicesHashMap = new HashMap<>();
mBTDevicesArrayList = new ArrayList<>();
adapter = new ListAdapter_BTLE_Devices(this, R.layout.btle_device_list_item, mBTDevicesArrayList);
ListView listView = new ListView(this);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
btn_Scan = (Button) findViewById(R.id.btn_scan);
((ScrollView) findViewById(R.id.scrollView)).addView(listView);
findViewById(R.id.btn_scan).setOnClickListener(this);
}
#Override
protected void onStart(){
super.onStart();
registerReceiver(mBTStateUpdateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
}
#Override
protected void onResume(){
super.onResume();
}
#Override
protected void onPause(){
super.onPause();
stopScan();
}
protected void onStop(){
super.onStop();
unregisterReceiver(mBTStateUpdateReceiver);
startScan();
}
#Override
protected void onDestroy(){
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_ENABLE_BT){
if (resultCode == RESULT_OK){
Utils.toast(getApplicationContext(),"Bluetooth is ready to use");
}
else if (resultCode == RESULT_CANCELED){
Utils.toast(getApplicationContext(),"Please turn on Bluetooth");
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_scan:
Utils.toast(getApplicationContext(),"Scan button pressed");
if(!mBTLeScanner.isScanning()){
startScan();
} else {
startScan();
}
break;
default:
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
public void addDevice(BluetoothDevice device, int new_rssi) {
String address = device.getAddress();
if(!mBTDevicesHashMap.containsKey(address)){
BTLE_Device btle_device = new BTLE_Device(device);
btle_device.setRssi(new_rssi);
mBTDevicesHashMap.put(address, btle_device);
mBTDevicesArrayList.add(btle_device);
} else {
mBTDevicesHashMap.get(address).setRssi(new_rssi);
}
adapter.notifyDataSetChanged();
}
public void startScan(){
btn_Scan.setText("Scanning...");
mBTDevicesArrayList.clear();
mBTDevicesHashMap.clear();
adapter.notifyDataSetChanged();
mBTLeScanner.start();
}
public void stopScan() {
btn_Scan.setText("Scan Again");
mBTLeScanner.stop();
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
onResume();
}
} else {
onDestroy();
}
return;
}
}
}
}
Here is the logcat:
2019-07-16 14:45:14.758 26071-26071/com.example.ble_scanner I/ple.ble_scanne: Not late-enabling -Xcheck:jni (already on)
2019-07-16 14:45:14.837 26071-26071/com.example.ble_scanner W/ple.ble_scanne: Unexpected CPU variant for X86 using defaults: x86
2019-07-16 14:45:14.935 26071-26079/com.example.ble_scanner E/ple.ble_scanne: Failed to send DDMS packet REAQ to debugger (-1 of 20): Broken pipe
2019-07-16 14:45:15.164 26071-26071/com.example.ble_scanner W/ple.ble_scanne: JIT profile information will not be recorded: profile file does not exits.
2019-07-16 14:45:15.166 26071-26071/com.example.ble_scanner I/chatty: uid=10096(com.example.ble_scanner) identical 10 lines
2019-07-16 14:45:15.166 26071-26071/com.example.ble_scanner W/ple.ble_scanne: JIT profile information will not be recorded: profile file does not exits.
2019-07-16 14:45:15.215 26071-26071/com.example.ble_scanner I/InstantRun: starting instant run server: is main process
2019-07-16 14:45:15.610 26071-26071/com.example.ble_scanner W/ple.ble_scanne: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2019-07-16 14:45:15.612 26071-26071/com.example.ble_scanner W/ple.ble_scanne: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2019-07-16 14:45:15.824 26071-26071/com.example.ble_scanner E/BluetoothAdapter: Bluetooth binder is null
2019-07-16 14:45:15.831 26071-26071/com.example.ble_scanner D/AndroidRuntime: Shutting down VM
2019-07-16 14:45:15.834 26071-26071/com.example.ble_scanner E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ble_scanner, PID: 26071
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ble_scanner/com.example.ble_scanner.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ScrollView.addView(android.view.View)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ScrollView.addView(android.view.View)' on a null object reference
at com.example.ble_scanner.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
In your xml layout try to check if the id of ScrollView is "scrollView", if not change it to scrollView the same as how you initialize in this line.
((ScrollView) findViewById(R.id.scrollView)).addView(listView);
or check your xml layout if ScrollView widget exist.
It throws the null pointer Exception because it cannot bind the layout, the id maybe misspelled or there is no scrollview widget in your layout.
Thank you everyone for your suggestion. The issue is solved. this code has two issue for which it did not work.
1. ((ScrollView) findViewById(R.id.scrollView)).addView(listView);
in this line scrollView is the wrong ID name. it should be the ID of your scrollview which for my case is device_list. it was making the app crash.
second issue is that i didnot call call for the permission function which will not give the list of BLE devices for android 6+ devices.

not able to display mp3 files in internal storage as list view on clicking a button

I've been trying to display all mp3 files in internal storage of a phone on clicking a button. But as soon as I click the button,it asks for storage permissions and after granting permissions, it says Unfortunately, app has stopped.Seems like I am getting run time exceptions but I can't find a way to resolve this. Can anyone help ?
This is the button :
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button3"
android:layout_alignStart="#+id/button3"
android:layout_below="#+id/button3"
android:layout_marginTop="22dp"
android:onClick="onClick3"
android:text="#string/button_audio" />
This is the class :
package com.example.dell_1.myapp3;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.io.IOException;
public class Bacon1 extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
private static int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
private String[] mAudioPath;
private MediaPlayer mMediaPlayer;
private String[] mMusicList;;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bacon1);
final Button button4 = (Button) findViewById(R.id.button4);
button4.setOnClickListener(
new View.OnClickListener(){
public void onClick (View v){
buttonClicked(v);
abc();
}
});
}
private void buttonClicked(View view){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Snackbar.make(view, "Permission not Granted, Requesting permission.", Snackbar.LENGTH_LONG).show();
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
Snackbar.make(view, "We need permission to internal storage for displaying songs", Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(view, "Allow myapp3 to access this device's internal storage", Snackbar.LENGTH_LONG).show();
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
public void onClick2(View view) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
public void onClick4(View view) {
Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
File file = Environment.getExternalStorageDirectory();
viewIntent1.setDataAndType(Uri.fromFile(file), "video/*");
startActivity(Intent.createChooser(viewIntent1, null));
}
public void onClick5(View view) {
Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
File file = Environment.getExternalStorageDirectory();
viewIntent1.setDataAndType(Uri.fromFile(file), "zip/*");
startActivity(Intent.createChooser(viewIntent1, null));
}
public void onClick6(View view) {
Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
File file = Environment.getExternalStorageDirectory();
viewIntent1.setDataAndType(Uri.fromFile(file), "text/*");
startActivity(Intent.createChooser(viewIntent1, null));
}
public void onClick7(View view) {
Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
File file = Environment.getExternalStorageDirectory();
viewIntent1.setDataAndType(Uri.fromFile(file), "application/*");
startActivity(Intent.createChooser(viewIntent1, null));
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(Bacon1.this, "WRITE_CONTACTS granted", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(Bacon1.this, "WRITE_CONTACTS Denied", Toast.LENGTH_SHORT)
.show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void abc(){
mMediaPlayer = new MediaPlayer();
ListView mListView = (ListView) findViewById(R.id.list);
mMusicList = getAudioList();
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mMusicList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
try {
playSong(mAudioPath[arg2]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private String[] getAudioList() {
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA }, null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
int count = mCursor.getCount();
String[] songs = new String[count];
String[] mAudioPath = new String[count];
int i = 0;
if (mCursor.moveToFirst()) {
do {
songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
i++;
} while (mCursor.moveToNext());
}
mCursor.close();
return songs;
}
private void playSong(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
Log.d("ringtone", "playSong :: " + path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
}
Here is the Android manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dell_1.myapp3">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_MEDIA_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_MEDIA_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<activity
android:name=".apples"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Bacon1"
android:label="#string/title_activity_bacon1" />
<activity
android:name=".SDCard"
android:label="#string/title_activity_sdcard" />
<activity
android:name=".Songmanager"
android:label="#string/title_activity_songmanager"></activity>
</application>
</manifest>
Here is the Logcat :
07-02 03:40:13.655 13229-13229/com.example.dell_1.myapp3 E/ExtMediaPlayer-JNI: env->IsInstanceOf fails
07-02 03:40:13.655 13229-13229/com.example.dell_1.myapp3 E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
07-02 03:40:13.655 13229-13229/com.example.dell_1.myapp3 E/ExtMediaPlayer-JNI: env->IsInstanceOf fails
07-02 03:40:13.655 13229-13229/com.example.dell_1.myapp3 E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
07-02 03:40:13.700 13229-13229/com.example.dell_1.myapp3 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dell_1.myapp3, PID: 13229
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.dell_1.myapp3.Bacon1.abc(Bacon1.java:158)
at com.example.dell_1.myapp3.Bacon1$1.onClick(Bacon1.java:48)
at android.view.View.performClick(View.java:5609)
at android.view.View$PerformClick.run(View.java:22263)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
You should add <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
to your manifest file.
You have ask for the permission at run time:
if (ContextCompat.checkSelfPermission(thisActivity,Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSION);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
and than do what ever you want (if the user grand the permission):
#Override
public void onRequestPermissionsResult(final int requestCode, #NonNull final String[] permissions, #NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
} else {
// User refused to grant permission.
}
}
}
You ca read more here:
https://developer.android.com/training/permissions/requesting.html

Write to external storage on Android 7

I want to write to the external storage in my Android app, but I don't seem to get the permissions right. The App runs on Android 7, so I request the permissions on runtime like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
int ACCESS_EXTERNAL_STORAGE_STATE = 1;
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
ACCESS_EXTERNAL_STORAGE_STATE);
}
permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
int ACCESS_EXTERNAL_STORAGE_STATE = 1;
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
ACCESS_EXTERNAL_STORAGE_STATE);
}
...
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case 1: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//reload my activity with permission granted or use the features what required the permission
} else
{
Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
One observation I made is that onRequestPermissionsResult seems to return that the permission was not granted, but I was also never prompted when starting the app to permit writing to external storage.
I set these permissions in the Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application>
The code to write to the storage is here:
public static void appendByteBuffer(byte[] data)
{
String filename = Environment.getExternalStorageDirectory().getAbsolutePath()+"/test.raw";
//filename value is "/storage/emulated/0/test.raw"
File rawAudioFile = new File(filename);
if (!rawAudioFile.exists())
{
try
{
rawAudioFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try (FileOutputStream output = new FileOutputStream(filename, true)) {
output.write(data);
} catch (IOException e) {}
}
03-16 14:50:49.988 19145-19306/? W/System.err: java.io.IOException:
Permission denied 03-16 14:50:49.988 19145-19306/? W/System.err:
at java.io.UnixFileSystem.createFileExclusively0(Native Method) 03-16
14:50:49.988 19145-19306/? W/System.err: at
java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
03-16 14:50:49.989 19145-19306/? W/System.err: at
java.io.File.createNewFile(File.java:948) 03-16 14:50:49.989
19145-19306/? W/System.err: at
com.meeter.study.AppUtils.appendByteBuffer(AppUtils.java:76) 03-16
14:50:49.989 19145-19306/? W/System.err: at
Use ContextCompat instead of ActivityCompat for checkSelfPermission:
Replace:
permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
With:
permission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
permission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
Then, Add onRequestPermissionsResult method to handle ALLOW, DENY selection. Hope this helps.
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case ACCESS_EXTERNAL_STORAGE_STATE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Write to the storage (ex: call appendByteBuffer(byte[] data) here)
} else {
Toast.makeText(getApplicationContext(), "Please grant permission.", Toast.LENGTH_LONG).show();
}
break;
}
}

java.lang.SecurityException: Sending SMS message: uid 10051 does not have android.permission.SEND_SMS [duplicate]

This question already has answers here:
Android permission doesn't work even if I have declared it
(11 answers)
Closed 1 year ago.
guys i have problem with sms manager about sms scheduled...in manifest i used
`<uses-permission android:name="android.permisson.SEND_SMS"/>`
but i get this error...i don't know why...i show you my LOGCAT:
FATAL EXCEPTION: main
Process: com.example.alarm, PID: 31456
java.lang.RuntimeException: Unable to start receiver com.example.alarm.AlarmReceiver: java.lang.SecurityException: Sending SMS message: uid 10051 does not have android.permission.SEND_SMS.
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2615)
at android.app.ActivityThread.access$1700(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5327)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.SecurityException: Sending SMS message: uid 10051 does not have android.permission.SEND_SMS.
at android.os.Parcel.readException(Parcel.java:1465)
at android.os.Parcel.readException(Parcel.java:1419)
at com.android.internal.telephony.ISms$Stub$Proxy.sendText(ISms.java:926)
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:156)
at com.example.alarm.AlarmReceiver.onReceive(AlarmReceiver.java:24)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2597)
at android.app.ActivityThread.access$1700(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:5327) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 
at dalvik.system.NativeStart.main(Native Method) 
and code about receiver broadcast:
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String phoneNumberReciver="123456";
String message="blablabla";
/*String SPhone =i.getStringExtra("exPhone");
String SSms = i.getStringExtra("exSmS");*/
//android.telephony.SmsManager sms= SmsManager.getDefault();
//sms.sendTextMessage(phoneNumberReciver, null, message, null, null);
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumberReciver, null, message, null, null);
Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG);
}
}
THIS IS MY MANIFEST:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarm"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="com.example.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permisson.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.alarm.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver"/>
</application>
</manifest>
WHO can help me? thanks in advance everybody!
Step 1
your menifest permission is
<uses-permission android:name="android.permisson.SEND_SMS"/>
update it with
<uses-permission android:name="android.permission.SEND_SMS"/>
its
android.permission.SEND_SMS not android.permisson.SEND_SMS
permission spelling is wrong
step2
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Copy and paste this code for sending sms services will done.
Button sendBtn = (Button)findViewById(R.id.senbtn);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
protected void sendSMSMessage() {
phoneNo = txtphoneNo.getText().toString();
message = txtMessage.getText().toString();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}
}
add this in menifest file:
<uses-permission android:name="android.permission.SEND_SMS"/>
The big reason for not getting your permission nowadays is because your project has a targetSdkVersion of 23 or higher, and the permission that you are requesting is "dangerous". In Android 6.0
you can give manually permission:
const onPermissionHandle = async () => {
// We need to ask permission for Android only
if (Platform.OS === 'android') {
// Calling the permission function
alert(granted);
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.SEND_SMS,
{
title: 'Example App SEND_SMS Permission',
message: 'Example App needs access to your SEND_SMS',
},
);
alert(granted);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
// Permission Granted
alert('You can use the SEND_SMS');
} else {
// Permission Denied
alert('SEND_SMS Permission Denied');
}
} else {
alert('You can use the SEND_SMS ');
}
};
you need to give runtime permission for OS marshmallow and above
go through this link
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//SEE NEXT STEP
}else{
sendSms();
}
if (checkSelfPermission(Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
//SEE NEXT STEP
} else {
sendSMS();
}
if (shouldShowRequestPermissionRationale(Manifest.permission.SEND_SMS)) {
//show some description about this permission to the user as a dialog, toast or in Snackbar
} else {
//request for the permission
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Snackbar.make(findViewById(R.id.rl), "Permission Granted",
Snackbar.LENGTH_LONG).show();
sendSMS();
} else {
Snackbar.make(findViewById(R.id.rl), "Permission denied",
Snackbar.LENGTH_LONG).show();
}
}
After hours of debugging, I found out that adding this permission to the xml file does not produce the error anymore:
<uses-permission-sdk-23 android:name="android.permission.READ_PHONE_STATE"/>

Android application not asking for camera permission

I am developing an SDK(.aar) which third parties can consume. In my sample application when I use the aar, I can see that the application doesnt prompt for the camera permission. When I open the aar and see its manifest.xm, it contains the below:
<!-- WRITE_EXTERNAL_STORAGE is needed because we are storing there the config files of KM -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.read_external_storage" />
<uses-permission android:name="com.samsung.android.providers.context.permission.WRITE_USE_APP_FEATURE_SURVEY" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.sensor.accelerometer" />
Since the camera is present as a required permission can anyone tell me why it is not coming up when installing the sample app.
Since Android 6.0 you have to request the permssions at runtime and the user is not prompted at the time of installation.
https://developer.android.com/training/permissions/requesting.html
Here is how i check for permissions:
public boolean permissionsGranted() {
boolean allPermissionsGranted = true;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
boolean hasWriteExternalPermission = (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
boolean hasReadExternalPermission = (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
boolean hasCameraPermission = (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED);
if (!hasWriteExternalPermission || !hasReadExternalPermission || !hasCameraPermission) {
allPermissionsGranted = false;
}
}
return allPermissionsGranted;
}
This is how i make the request if permissionsGranted() method returns false
String[] permissions = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA, android.Manifest.permission.READ_EXTERNAL_STORAGE};
ActivityCompat.requestPermissions(this, permissions, 1);
And you have to override onRequestPermissionsResult method, below is what i have in mine.
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1: {
boolean startActivity = true;
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] != PackageManager.PERMISSION_GRANTED) {
String permission = permissions[i];
boolean showRationale = shouldShowRequestPermissionRationale(permission);
if (!showRationale) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
intent.setData(uri);
startActivityWithIntent(intent);
Toast.makeText(this, "Enable required permissions", Toast.LENGTH_LONG).show();
startActivity = false;
break;
} else {
Toast.makeText(this, "Enable required permissions", Toast.LENGTH_LONG).show();
break;
}
}
}
if(startActivity) {
getActivity().finish();
startActivityWithIntent(getIntent());
}
}
}
}
public void startActivityWithIntent(Intent intent){
startActivity(intent);
}
showRationale is to check if user ticked never ask again, if so then i start the settings activity so that user can enable permissions.
Let me know if you need more clarity

Categories