Android 6 Error in Reading Device ID? [closed] - android

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
While Reading Device ID etc. I am getting an error in Android 6.
How ever its working fine in all other versions 4.0,5.1 etc..
This is my code:
public class MyDevIDS extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
PackageInfo pInfo = null;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
String version = pInfo.versionName;
TextView versionText = (TextView) findViewById(R.id.tv7);
versionText.setText("Version : " + version);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imei_id = telephonyManager.getDeviceId();
TextView imei_idT = (TextView) findViewById(R.id.tv9);
String imei_idV = "<b><font color=#008000>" + imei_id + "</b></font>";
imei_idT.setText(Html.fromHtml("IMEI ID : " + imei_idV));
String device_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
TextView device_idT = (TextView) findViewById(R.id.tv10);
String device_idV = "<b><font color=#008000>" + device_id + "</b></font>";
device_idT.setText(Html.fromHtml("Device ID : " + device_idV));
}
}
this is error I am getting
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.devid/com.test.devid.MyDevIDS}: java.lang.SecurityException: getDeviceId: Neither user 10102 nor current process has android.permission.READ_PHONE_STATE.
How ever I Have given permission in manifest.. but I need to give Run time permissions in Android 6...
For that I followed this
https://developer.android.com/training/permissions/requesting.html
But I tried but its notworking..
Can any one suggest me how to use Run time permissions in my code..

public class MyDevIDS extends AppCompatActivity {
private static final int REQUEST_READ_PERMISSION = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
if (CheckPermission(this, Manifest.permission.READ_PHONE_STATE)) {
YourStuffHandling();
} else {
RequestPermission(MyDevIDS.this, Manifest.permission.READ_PHONE_STATE, REQUEST_READ_PERMISSION );
}
}
private void YourStuffHandling() {
PackageInfo pInfo = null;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String version = pInfo.versionName;
TextView versionText = (TextView) findViewById(R.id.tv7);
versionText.setText("Version : " + version);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imei_id = telephonyManager.getDeviceId();
TextView imei_idT = (TextView) findViewById(R.id.tv9);
String imei_idV = "<b><font color=#008000>" + imei_id + "</b></font>";
imei_idT.setText(Html.fromHtml("IMEI ID : " + imei_idV));
String device_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
TextView device_idT = (TextView) findViewById(R.id.tv10);
String device_idV = "<b><font color=#008000>" + device_id + "</b></font>";
device_idT.setText(Html.fromHtml("Device ID : " + device_idV));
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
switch (permsRequestCode) {
case REQUEST_READ_PERMISSION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
YourStuffHandling();
} else {
ShowToast(getString(R.string.permission_needed_sms));
}
return;
}
}
}
public void RequestPermission(Activity thisActivity, String Permission, int Code) {
if (ContextCompat.checkSelfPermission(thisActivity,
Permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Permission)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Permission},
Code);
}
}
}
public boolean CheckPermission(Context context, String Permission) {
if (ContextCompat.checkSelfPermission(context,
Permission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
}

Android sdk has implemented Runtime permission feature from version 6.0 onwards. No matter weather you have given permission in manifest file you need to check that permission before you access.
You can check at runtime using either hasSystemFeature(PackageManager.FEATURE_TELEPHONY) or getPhoneType().
Or you can check by following format I have done for Camera permission
public void getCameraPermission(){
if (!checkPermission()) {
requestPermission();
}
}
private boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
private void requestPermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CAMERA)){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,"Permission granted",Toast.LENGTH_SHORT).show();
//store permission in shared pref
}
else {
Toast.makeText(MainActivity.this,"Permission denied",Toast.LENGTH_SHORT).show();
//store permission in shared pref
}
break;
}
}

Related

Neither user 10085 nor current process has android.permission.READ_PHONE_STATE

I have updated target sdk version 27 and i have given permission in manifest of READ_PHONE_STATE. Still my app is crashing on utils.java
deviceId = TelephonyMgr.getDeviceId();
on this line and i also ask for run time permission for this still the issue is same
private void RequestMultiplePermission() {
// Creating String Array with Permissions.
ActivityCompat.requestPermissions(LoginActivity.this, new String[]
{
CALL_PHONE,
READ_PHONE_STATE
}, RequestPermissionCode);
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean GetCallPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean GetReadphoneper = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (GetCallPermission && GetReadphoneper) {
Toast.makeText(LoginActivity.this, "Permission Granted", Toast.LENGTH_LONG).show();
}
else {
///Toast.makeText(Login.this,"Permission Granted",Toast.LENGTH_LONG).show();
}
}
break;
}
}
here in this line it will crash
deviceId = TelephonyMgr.getDeviceId();
public static String getUniqueDeviceId(Context context) {
String deviceId;
// 1 compute IMEI
final TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
}
deviceId = TelephonyMgr.getDeviceId(); // Requires // READ_PHONE_STATE
if (deviceId == null) {
// 2 android ID - unreliable
deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
}
if (deviceId == null) {
Random r = new Random();
deviceId = String.valueOf((r.nextInt() + r.nextInt()));
}
e(deviceId);
return deviceId;
}
Solved using this::
deviceId = Settings.Secure.getString(context.getContentResolver(),
InstanceID.getInstance(context).getId());

IMEI Getting null for the first time when we install application Android

I have tried different links but none of them works:
TelephonyManager returns null for IMEI number: what can cause this?
How to get device's IMEI/ESN number with code programming But in android > 6
and many more links but none of them working.
This is my Utils Class:
public static String getIMEINumber(Context context){
TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getDeviceId();
}
Calling below code from my Activity:
String deviceIMEI = Utils.getIMEINumber(LoginActivity.this);
But this is giving me null sometimes (when we install App for the first time particularly).Can you help me on this?
Thank you very much for your time and assistance in this matter.
See sample:
private int REQUEST_PERMISSION_PHONE_STATE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showPhoneStatePermission();
}
private void showPhoneStatePermission() {
int permissionCheck = ContextCompat.checkSelfPermission(
this, Manifest.permission.READ_PHONE_STATE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
requestPermission(Manifest.permission.READ_PHONE_STATE, REQUEST_PERMISSION_PHONE_STATE);
} else {
getIMEI();
}
}
private void getIMEI() {
String deviceId = IMEIUtil.getDeviceId(this);
toastMessage(deviceId);
}
private void requestPermission(String permissionName, int permissionRequestCode) {
ActivityCompat.requestPermissions(this,
new String[]{permissionName}, permissionRequestCode);
}
private void toastMessage(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION_PHONE_STATE) {
showPhoneStatePermission();
}
}
And class IMEIUtil:
public static String getDeviceId(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String deviceId = telephonyManager.getDeviceId().trim();
if (deviceId == null) {
String androidId = Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ANDROID_ID);
deviceId = android.os.Build.SERIAL + "#" + androidId;
}
return deviceId.trim();
}
Require add permission <uses-permission android:name="android.permission.READ_PHONE_STATE" /> before tag <application> on AndroidManifest. You can see full code: https://github.com/HoangDang/GetIMEI/tree/master/GetIMEI. I hope it can help you!

How to get currently ongoing call duration after user ends a call in android?

I am calling from my app. After ends that call, I am trying to get a call duration. But my code return call duration two times. Last call duration while making call and new call duration after ends a call. But I need only one call duration after user ends the new call. How can i achieve this. Here is my code. Thanks in advance.
public class MainActivity extends AppCompatActivity {
private static final int CALL_PERMISSION= 99;
private static final int READ_LOG_PERMISSION=11;
Button btnGetCallDuration;
Context mContext;
private int mFlag = 0;
String phNumber = "";
boolean flag=false;
String callDuration = "";
public static int REQ_CODE=1;
private boolean callPermission=false;
private boolean readlogPermission=false;
public static final int MULTIPLE_PERMISSIONS = 10; // code you want.
String[] permissions = new String[] {
Manifest.permission.READ_CALL_LOG,
Manifest.permission.CALL_PHONE,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = MainActivity.this;
btnGetCallDuration = (Button) findViewById(R.id.btnGetCallDuration);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermissions();
}
btnGetCallDuration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("onclick", "called");
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:121"));
startActivity(intent);
//flag = true;
}
});
}
private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(mContext,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new
String[listPermissionsNeeded.size()]), MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("request code",requestCode+"\t"+resultCode);
if(requestCode==REQ_CODE)
{
Log.v("request code",requestCode+"");
// getCallDruation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MULTIPLE_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permissions granted.
callPermission=true;
} else {
// no permissions granted.
callPermission=false;
}
return;
}
}
}
#Override
protected void onPause() {
super.onPause();
Log.v("Pause is called","pause");
flag=true;
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.CALL_PHONE)) {
// 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.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
CALL_PERMISSION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
CALL_PERMISSION);
}
return false;
} else {
return true;
}
}
public boolean readCallLogPermission() {
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.READ_CALL_LOG)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.READ_CALL_LOG)) {
// 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.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CALL_LOG},
READ_LOG_PERMISSION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
READ_LOG_PERMISSION);
}
return false;
} else {
callPermission=true;
return callPermission;
}
}
#Override
protected void onResume() {
super.onResume();
Log.v("flag","onrsume called");
if(flag)
{
getCallDruation();
flag=false;
}
}
private void getCallDruation() {
StringBuffer sb = new StringBuffer();
Uri contacts = CallLog.Calls.CONTENT_URI;
Log.v("get duration","called");
Cursor cur = getContentResolver().query(contacts, null, null, null, android.provider.CallLog.Calls.DATE + " DESC");
int number = cur.getColumnIndex(CallLog.Calls.NUMBER);
int duration = cur.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details : \n");
while (cur.moveToNext()) {
phNumber = cur.getString(number);
callDuration = cur.getString(duration);
sb.append("\nPhone Number:" + phNumber+"\t"+callDuration);
break;
}
cur.close();
String str = sb.toString();
Log.v("restult",str);
Toast.makeText(mContext, phNumber + "\t\t" + callDuration, Toast.LENGTH_SHORT).show();
}
}
This above code is called from onResume() life cycle method of activity.

Measure mobile data usage from a particular point of time

I want to use a service to measure the mobile data used since that service is started but I'm only able to measure the mobile data since device boot using the methods getTotalRxBytes() and getTotalTxBytes() of the TrafficStats class. Can someone help me in measuring the data used when the button is clicked and the service is started?
MainActivity.java
public class MainActivity extends AppCompatActivity {
private long data_limit;
EditText et_data_limit;
Button btn_start_track;
private int STORAGE_PERMISSION_CODE = 23;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
int PRIVATE_MODE = 0;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = MainActivity.this.getSharedPreferences("Data measured", PRIVATE_MODE);
editor = sharedPreferences.edit();
editor.putLong("data", 0);
if(isPermissionAllowed()){
}
else{
requestPermission();
}
et_data_limit = (EditText)findViewById(R.id.et_data_limit);
btn_start_track = (Button)findViewById(R.id.btn_start_track);
btn_start_track.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data_limit = Long.parseLong(et_data_limit.getText().toString());
data_limit = data_limit * 1024;
Log.i("enter", String.valueOf(data_limit));
//data_limit = data_limit + sharedPreferences.getLong("data", 0);
editor.putLong("data", data_limit);
editor.commit();
Intent intent = new Intent(MainActivity.this, DataTracking.class);
intent.putExtra("data limit", data_limit);
MainActivity.this.startService(intent);
}
});
}
private boolean isPermissionAllowed() {
//Getting the permission status
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE);
int result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE);
int result2 = ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_PHONE_STATE);
//If permission is granted returning true
if (result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED &&
result2 == PackageManager.PERMISSION_GRANTED)
return true;
//If permission is not granted returning false
return false;
}
private void requestPermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_WIFI_STATE) &&
ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CHANGE_WIFI_STATE) &&
ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.MODIFY_PHONE_STATE)){
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.MODIFY_PHONE_STATE},STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if(requestCode == STORAGE_PERMISSION_CODE){
//If permission is granted
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Displaying a toast
Toast.makeText(this,"Permission granted!",Toast.LENGTH_LONG).show();
}else{
//Displaying another toast if permission is not granted
Toast.makeText(this,"Permission denied! App may not work properly",Toast.LENGTH_LONG).show();
}
}
}
}
DataTracking.java
public class DataTracking extends Service {
private long data_limit;
private long data_used;
public DataTracking(){
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
data_limit = intent.getExtras().getLong("data limit");
Log.i("data", String.valueOf(data_limit));
Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_SHORT).show();
onHandleIntent(intent);
return Service.START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
protected void onHandleIntent(#Nullable Intent intent) {
TrafficStats trafficStats = new TrafficStats();
long mtx = TrafficStats.getMobileTxBytes();
long mrx = TrafficStats.getMobileRxBytes();
data_used = mtx + mrx;
Toast.makeText(getApplicationContext(), data_used + "-" + data_limit, Toast.LENGTH_SHORT).show();
if(data_used >= data_limit){
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
try{
TelephonyManager telephonyManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
Method setMobileDataStatus = telephonyManager.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
if (null != setMobileDataStatus){
setMobileDataStatus.invoke(telephonyManager, false);
stopSelf();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
}

Android: Function is not excuting with runtime permissions in Android

In the below code,getInfoFromDevice is not being executed, I also tried with a Log.d() but it could not be of further help.
In the code I am using runtime permissions to check if the user has granted permission to access external storage and if yes the function getInfoFromDevice() is called. I am not sure if the placement of the function is correct or not ? But this function is not executing. what could be the reason ?
It does not throw any error,
public class MainActivity extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback {
ArrayList<String> listOfSongs = new ArrayList<String>();
ListView liststructure;
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
String MUSIC_STRING = MediaStore.Audio.Media.IS_MUSIC + "!=0";
String[] STAR = {"*"};
String orderColumns = MediaStore.Audio.AudioColumns.TITLE + " COLLATE LOCALISED ASC";
private final int REQUEST_GRANTED_BY_USER = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermissions();
liststructure = (ListView) findViewById(R.id.listView);
SongsList list = new SongsList(MainActivity.this, listOfSongs);
liststructure.setAdapter(list);
}
private void checkPermissions() {
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_GRANTED_BY_USER);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode == REQUEST_GRANTED_BY_USER )
{
getInfoFromDevice();
} else {
// Permission Denied
Toast.makeText(MainActivity.this, "EXTERNAL_STORAGE Denied", Toast.LENGTH_SHORT)
.show();
}
}
void getInfoFromDevice() {
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, STAR, MUSIC_STRING, null, null);
if (cursor != null)
{
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
String albumID = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
listOfSongs.add(album + " " + name + " " + albumID);
} while (cursor.moveToNext());
}
}
}
}
Please let me know if you need more details.
EDIT 1
The code will look for mp3 files with the help of MediaStore library and will check if it has a permission to access external storage and if yes it will call the function getInfoFromDevice()
just change you code like below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
liststructure = (ListView) findViewById(R.id.listView);
SongsList list = new SongsList(MainActivity.this, listOfSongs);
liststructure.setAdapter(list);
checkPermissions();
}
private void checkPermissions() {
if (Build.VERSION.SDK_INT >= 23) {
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_GRANTED_BY_USER);
}else{
getInfoFromDevice();
}
}else{
getInfoFromDevice();
}
}
First check permission as below,
public void checkPermission(String permission) {
if (ContextCompat.checkSelfPermission(BaseActivity.this,
permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(BaseActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(BaseActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
10);
} else {
ActivityCompat.requestPermissions(BaseActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
10);
}
}
}
then,
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 10: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
// permission granted call your function
getInfoFromDevice();
} else {
// permission denied.
}
return;
}
}
}
You can also use below plugin to easily add run time permission without more effort,
https://android-arsenal.com/details/1/3571

Categories

Resources