skip to Main Content

How can I get the last call number without using the READ_CALL_LOG permission?

2

Answers


  1. Not possible without permission

    Login or Signup to reply.
  2. 1.Add the required permissions to your AndroidManifest.xml file:

    <uses-permission android:name="android.permission.READ_CALL_LOG" />
    

    2.In your activity or fragment class, import the necessary classes:

    import android.Manifest;
    import android.content.pm.PackageManager;
    import android.database.Cursor;
    import android.provider.CallLog;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    

    3.Check and request the necessary permissions:

    private static final int PERMISSION_REQUEST_READ_CALL_LOG = 1;
    
    // Check if the READ_CALL_LOG permission is granted
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
        // Permission is not granted, request it
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALL_LOG}, PERMISSION_REQUEST_READ_CALL_LOG);
    } else {
        // Permission is already granted, proceed with retrieving the last call number
        getLastCallNumber();
    }
    

    4.Handle the permission request result:

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_READ_CALL_LOG) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted, retrieve the last call number
                getLastCallNumber();
            } else {
                // Permission denied, handle accordingly (e.g., display an error message)
            }
        }
    }
    

    5.Implement the method to retrieve the last call number:

    private void getLastCallNumber() {
        Cursor cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, CallLog.Calls.DATE + " DESC");
        if (cursor != null && cursor.moveToFirst()) {
            String lastCallNumber = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
            // Use the lastCallNumber as needed
            cursor.close();
        }
    }
    

    In the getLastCallNumber() method, we query the CallLog content provider to retrieve the call log data ordered by date in descending order. We extract the number of the first entry (which will be the last call) and store it in the lastCallNumber variable.

    Make sure to handle any necessary error checking, null checks, and close the cursor properly.

    Remember to handle the case where the permission is denied and provide appropriate feedback or alternative behavior in your application.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search