2017-03-13 51 views
-1

我創建了一個簡單的android活動,充當撥號。 它有一個電話號碼和一個呼叫按鈕 這裏一個EditText是代碼:(安卓6.0棉花糖)如何檢查權限是否由運行時用戶在Android上授予?

public class Main2Activity extends AppCompatActivity { 
EditText num; 
Button call; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main2); 
    num = (EditText) findViewById(R.id.num); 
    call = (Button) findViewById(R.id.call); 
    call.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      try { 
       // request permission if not granted 
       if (ActivityCompat.checkSelfPermission(Main2Activity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { 
        ActivityCompat.requestPermissions(Main2Activity.this, new String[]{Manifest.permission.CALL_PHONE}, 123); 
        // i suppose that the user has granted the permission 
        Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + num.getText().toString())); 
        startActivity(in); 
       // if the permission is granted then ok 
       } else { 
        Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + num.getText().toString())); 
        startActivity(in); 
       } 
      } 
      // catch the exception if i try to make a call and the permission is not granted 
      catch (Exception e){ 
      } 
     } 
    }); 
} 

}

當我跑我的應用程序,有問題

  • 如果我點擊通話按鈕並授予權限,則意圖不會被調用,直到我再次點擊

  • 我不知道如何o或檢查的權限被授予不

+0

你可以嘗試下面的鏈接http://stackoverflow.com/questions/42136340/not-able-to-get-android-run-time-permission-result/42136548#42136548 –

回答

2

使用onRequestPermissionResult,它處理的行動,如果用戶按ALLOWDENY,只需調用中的條件意圖「如果用戶按下允許」:

@Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
     super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
     switch (requestCode) { 
      case 123: { 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        //If user presses allow 
        Toast.makeText(Main2Activity.this, "Permission granted!", Toast.LENGTH_SHORT).show(); 
        Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + num.getText().toString())); 
       startActivity(in); 
       } else { 
        //If user presses deny 
        Toast.makeText(Main2Activity.this, "Permission denied", Toast.LENGTH_SHORT).show(); 
       } 
       break; 
      } 
     } 
    } 

希望這會有所幫助。

+0

我試過了,但是當我拒絕許可麪包不顯示 –

+0

現在請檢查。 – tahsinRupam

+1

它現在正在工作謝謝 –

相關問題