Java android studio中的运行时权限

Java android studio中的运行时权限,java,android-studio,Java,Android Studio,我已经创建了一个可以发送消息和拨打电话的应用程序(仅在授予权限的情况下) 我已经尝试过通过手动允许访问我的短信和电话的权限来使用我的手机设置发送短信或拨打电话 这是我的代码(PhoneApp.java) XML代码(myphone.XML) 我希望我的应用程序只有在我点击“发送短信”按钮时才请求许可,而不是每次我进入上述页面时,我的应用程序都请求许可(而不是点击“发送短信”按钮)。但巴顿的情况并非如此。它工作得很好(只有在我点击“呼叫”按钮后才请求许可) 如果您能以代码片段的形式提供解决方案

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

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

这是我的代码(PhoneApp.java)

XML代码(myphone.XML)


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


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

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

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

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


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

您请求在事件处理程序中调用的
makeCall
中进行调用的权限。您可以在
onCreate
中请求SMS权限,而不是在事件处理程序中。
package com.example.phone;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.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);
                }
            }
        }
    }

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

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



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

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

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

</RelativeLayout>
@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();
        }
    });
}