简体   繁体   中英

How to properly ask for permissions on Runtime?

Hi im making an application using Android Studios the requires 3 permissions in total

CALL_PHONE, READ_CONTACTS, RECORD_AUDIO.

im kinda very new to development and thats why my coding is a bit sloppy(no kidding), when I run the app it doesnt asks for the permission and doesnt work but if i manually go to setting and grant the permissions it works fine Im using fragments and writing the code in the fragment class is that wrong or should i write this code in my mainActivity.java Im attaching both please look at my code and how can I improve it If I have to work from the scratch im ok with it.

DialerActivity.java:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;


public class DialerActivity extends FragmentActivity {

private static final String FRAGMENT_TAG_DIALER = "fragment:dialer";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dialer);

    FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = (DialerFragment) fm.findFragmentByTag(FRAGMENT_TAG_DIALER);

        if(fragment == null){
            fragment = new DialerFragment();
            fm.beginTransaction()
                    .add(R.id.fragment_container,fragment, FRAGMENT_TAG_DIALER)
                    .commit();
        }
}
}

DialerFragmnet.java:

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;;
import android.support.v4.content.ContextCompat;


public class DialerFragment extends Fragment {
  private EditText mPhoneField;
  private Button mDialButton;

//Requesting Permissions on Runtime.
final private int REQUEST_CODE_ASK_PERMISSIONS=0;

private void InitiateCall(){
    int hasCallPermission = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.READ_PHONE_STATE);
    if (hasCallPermission != PackageManager.PERMISSION_GRANTED){
        requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},
                REQUEST_CODE_ASK_PERMISSIONS);
        return;
    }
    InitiateCall();
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults ){
   switch (requestCode){
       case REQUEST_CODE_ASK_PERMISSIONS:
           if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
               //YAY! PERMISSION GRANTED
               InitiateCall();
           }else{
               //GD! PERMISSION DENIED
               Toast.makeText(getActivity(), R.string.permission_denied, Toast.LENGTH_SHORT).show();
           }
            break;
       default:
           super.onRequestPermissionsResult(requestCode, permissions, grantResults);

   }
}



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
    View v=inflater.inflate(R.layout.fragment_dialer,container,false);

    mPhoneField=(EditText) v.findViewById(R.id.input_pno);
    mDialButton=(Button) v.findViewById(R.id.dial_button);

    mDialButton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            try{
                if (mPhoneField != null && (mPhoneField.getText().length()==10||mPhoneField.getText().length()==11)){
                    startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mPhoneField.getText())));
                }
                else if(mPhoneField != null && mPhoneField.getText().length()==0){
                    Toast.makeText(getActivity(),R.string.no_number_toast,Toast.LENGTH_SHORT).show();
                }
                else if(mPhoneField !=null && mPhoneField.getText().length()<10){
                    Toast.makeText(getActivity(),R.string.wrong_number_toast,Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e){
                Log.e("DialerAppActivity","error: " + e.getMessage(),e);//Runtime error will be logged
            }
        }
    });


    return v;
}

}

You actually never call your method that ask the permission. Your method : InitiateCall should not call itself, because it'll create an infiniteLoop. So you should modify it to be this way:

private void InitiateCall(){
    int hasCallPermission = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.READ_PHONE_STATE);
    if (hasCallPermission != PackageManager.PERMISSION_GRANTED){
        requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},
                REQUEST_CODE_ASK_PERMISSIONS);
        return;
    }
}

and you can call InitiateCall at the end of the onCreateView .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM