Разрешение Action_Call не предоставлено в Android Studio - PullRequest
1 голос
/ 07 мая 2020

Я пытаюсь создать приложение, которое может напрямую звонить, если номер введен, но разрешение не предоставлено и, следовательно, звонок не производится ...

Я запросил разрешение в AndriodManifest. xml

Каждый раз, когда я ввожу число, выскакивает сообщение «Привет», которое написано, если разрешено не разрешено. Мой код:

MainActivity. java

package com.example.block9;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void redirectmessage(View v) {
        String number = (((EditText) findViewById(R.id.mobnumber)).getText()).toString();
        String message = (((EditText) findViewById(R.id.textmessage)).getText()).toString();
        Uri num = Uri.parse("smsto:" + number);
        Intent smsIntent = new Intent(Intent.ACTION_SENDTO, num);
        smsIntent.putExtra("sms_body", message);
        startActivity(smsIntent);
    }

    public void redirectcall(View v) {
        String number = (((EditText) findViewById(R.id.mobnumber)).getText()).toString();
        Toast t = null;
        //t.makeText(getApplicationContext(),number,Toast.LENGTH_SHORT).show();
        Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:" + number));
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            t.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
            return;
        }
        startActivity(callIntent);
    }
}

AndroidManifest. xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.block9">

    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <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>

Любые Помощь будет признательна !! `введите здесь код.

1 Ответ

0 голосов
/ 07 мая 2020

Если ваше целевое устройство API is <22, вам не нужно запрашивать разрешение, поскольку разрешение будет предоставлено автоматически. Но как разработчик вы должны быть готовы ко всем возможностям. в случае, если целевое устройство API is >=23, вам нужно вручную запросить разрешение. Для получения дополнительной информации об этом Прочтите this

public void redirectcall(View v) {
            String number = (((EditText) findViewById(R.id.mobnumber)).getText()).toString();
            Toast t = null;
            //t.makeText(getApplicationContext(),number,Toast.LENGTH_SHORT).show();
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + number));
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                t.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();

                grantPermission();

                return;
            }
            startActivity(callIntent);
        }

    private void grantPermission() {

          // show your dialog box to ask for permission
            new AlertDialog.Builder(this)
                    .setTitle("Call Permission Required")
                    .setMessage("This App needs Call permission, to function properly")
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    })
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //here permission will be given
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 3); // 3 is requestCode and can be any number
                        }
                    })
                    .create()
                    .show();
    }

После отправки запроса мы вызовем метод @Override onRequestPermissionsResult() для обработки сценария отклоненного или принятого запроса

*@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 3: //remember that 3 is the same number which we specified while requesting
            {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // Call-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.CALL_PHONE)
                            == PackageManager.PERMISSION_GRANTED) {
                        redirectcall();
                    }


                }else{
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }

            }

        }
    }*

Full MainActivity. java код здесь: https://gist.github.com/Shoaibpython/eda5394ee4bc441396d68d5ef603cd3

Пожалуйста, ответьте здесь, если вы заметили какую-либо ошибку.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...