有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓 studio中的java运行时权限

我已经创建了一个可以发送消息和拨打电话的应用程序(仅在授予权限的情况下)

我已经尝试过通过手动允许访问我的短信和电话的权限来使用我的手机设置发送短信或拨打电话

这是我的代码(PhoneApp.java)

package com.example.phone;

import 安卓.Manifest;
import 安卓.app.Activity;
import 安卓.content.Intent;
import 安卓.content.pm.PackageManager;
import 安卓.net.Uri;
import 安卓.os.Bundle;
import 安卓.support.v4.app.ActivityCompat;
import 安卓.support.v4.content.ContextCompat;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.support.v7.widget.Toolbar;
import 安卓.telephony.SmsManager;
import 安卓.util.Log;
import 安卓.view.Menu;
import 安卓.view.View;
import 安卓.view.View.OnClickListener;
import 安卓.widget.Button;
import 安卓.widget.EditText;
import 安卓.widget.Toast;


public class PhoneApp extends AppCompatActivity {
    private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
    private Toolbar mTopToolbar;
    private static final int REQUEST_PHONE_CALL = 1;
    Button sendBtn;
    EditText txtMessage;
    EditText edittext1;
    Button button1;
    String phoneNo;
    String message;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myphone);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //Getting the edittext and button instance
        edittext1=(EditText)findViewById(R.id.editText);
        button1=(Button)findViewById(R.id.btnCall);
        sendBtn = (Button) findViewById(R.id.btnSendSMS);
        txtMessage = (EditText) findViewById(R.id.editText2);

        //Performing action on button click
        button1.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                makeCall();
            }



        });

        sendBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(
                        edittext1.getText().toString(),
                        null,
                        txtMessage.getText().toString(),
                        null,
                        null);

                Toast.makeText(getApplicationContext(), "SMS sent.",
                        Toast.LENGTH_LONG).show();
            }
        });

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
            Log.d("PLAYGROUND", "Permission is not granted, requesting");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, MY_PERMISSIONS_REQUEST_SEND_SMS);
            sendBtn.setEnabled(false);
        } else {
            Log.d("PLAYGROUND", "Permission is granted");
        }
    }

    Intent intent = new Intent(Intent.ACTION_CALL);

    protected void makeCall() {
        String number=edittext1.getText().toString();
        intent.setData(Uri.parse("tel:"+number));
        if (ContextCompat.checkSelfPermission(PhoneApp.this,
                Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(PhoneApp.this,
                    new String[]{Manifest.permission.CALL_PHONE},REQUEST_PHONE_CALL);
        }
        else
        {
            startActivity(intent);
        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
        switch (requestCode) {

            case REQUEST_PHONE_CALL: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(getApplicationContext(), "Calling....",
                            Toast.LENGTH_LONG).show();
                    startActivity(intent);
                }
                else
                {
                    Toast.makeText(getApplicationContext(),
                            "Unable to connect", Toast.LENGTH_LONG).show();
                    return;
                }
                return;
            }
            case MY_PERMISSIONS_REQUEST_SEND_SMS: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("PLAYGROUND", "Permission has been granted");
                    Toast.makeText(getApplicationContext(),
                            "You can send SMS", Toast.LENGTH_LONG).show();
                    sendBtn.setEnabled(true);
                } else {
                    Log.d("PLAYGROUND", "Permission has been denied or request cancelled");
                    Toast.makeText(getApplicationContext(),
                            "Unable to connect", Toast.LENGTH_LONG).show();
                    sendBtn.setEnabled(false);
                }
            }
        }
    }

}

XML代码(myphone.XML)

<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    tools:context=".PhoneApp">

    <安卓.support.v7.widget.Toolbar
        安卓:id="@+id/toolbar"
        安卓:minHeight="?attr/actionBarSize"
        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content"
        app:titleTextColor="@安卓:color/white"
        安卓:background="?attr/colorPrimary">
    </安卓.support.v7.widget.Toolbar>



    <EditText
        安卓:id="@+id/editText"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:layout_alignParentTop="true"
        安卓:hint="@string/phone_number"
        安卓:layout_alignParentRight="true"
        安卓:layout_marginTop="88dp"
        安卓:layout_marginRight="109dp"
        安卓:ems="10" />

    <EditText
        安卓:id="@+id/editText2"
        安卓:layout_width="200dp"
        安卓:layout_height="wrap_content"
        安卓:layout_below="@+id/editText"
        安卓:layout_alignLeft="@+id/editText"
        安卓:layout_marginLeft="6dp"
        安卓:layout_marginTop="65dp"
        安卓:hint="@string/type_your_message"
        安卓:ems="10"
        安卓:inputType="textMultiLine" />
    <Button
        安卓:id="@+id/btnSendSMS"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:layout_marginLeft="90dp"
        安卓:layout_below="@+id/editText2"
        安卓:layout_marginTop="60dp"
        安卓:text="Send Sms" />

    <Button
        安卓:id="@+id/btnCall"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:layout_alignParentTop="true"
        安卓:layout_marginTop="302dp"
        安卓:layout_marginLeft="270dp"
        安卓:text="Call" />

</RelativeLayout>

这是我的设计:

enter image description here

我希望我的应用程序只有在我点击“发送短信”按钮时才请求许可,而不是每次我进入上述页面时,我的应用程序都请求许可(而不是点击“发送短信”按钮)。但巴顿的情况并非如此。它工作得很好(只有在我点击“呼叫”按钮后才请求许可)

如果您能以代码片段的形式提供解决方案来帮助我解决这个问题,那就太好了。对不起,我的英语不好。提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    解决方案很简单,只需将onCreate()更改为:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myphone);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //Getting the edittext and button instance
        edittext1 = (EditText) findViewById(R.id.editText);
        button1 = (Button) findViewById(R.id.btnCall);
        sendBtn = (Button) findViewById(R.id.btnSendSMS);
        txtMessage = (EditText) findViewById(R.id.editText2);
    
        //Performing action on button click
        button1.setOnClickListener(this::makeCall());
    
        sendBtn.setOnClickListener((view) - >{
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                Log.d("PLAYGROUND", "Permission is not granted, requesting");
                ActivityCompat.requestPermissions(this, new String[] {
                    Manifest.permission.SEND_SMS
                },
                MY_PERMISSIONS_REQUEST_SEND_SMS);
            } else {
                Log.d("PLAYGROUND", "Permission is granted");
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(
                edittext1.getText().toString(), null, txtMessage.getText().toString(), null, null);
    
                Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
            }
        });
    }
    

    问题是您在onCreate()函数中请求发送消息的权限,但要使其按需要工作,您必须从按钮的onClick()侦听器请求权限

    就在这个主题上,我通过更改为lambda函数格式化了您的代码

    希望这能解决你的问题。如果您愿意,我很乐意解释我更改的代码的任何部分