2017-03-20 17 views
1

私はAndroidで新しく、実行時のアクセス権に問題があります。 私のアプリは電話のすべての連絡先を読んでリストを抽出します。問題は私の電話の連絡先を読む許可です。私が初めてアプリを開くと、アプリがクラッシュしてから連絡先を読む許可を求めます。 もう一度開くと、2回目にアプリに問題があります。 だから、問題がクラッシュする前に許可を求めることです... 私MainActivityは次のとおりです。もちろんAndroid Nougat実行時アクセス許可

public class MainActivity extends AppCompatActivity { 
    public static final int REQUEST_CODE_ASK_PERMISSIONS = 123; 
    ReadContacts values = new ReadContacts(); 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // Readcontacts val = new Readcontacts(); 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     // Get ListView object from xml 

/* 
     int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.READ_CONTACTS); 
     if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) { 
      requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 
        REQUEST_CODE_ASK_PERMISSIONS); }*/ 
     final ListView listView = (ListView) findViewById(R.id.list); 
     final int frth = listView.getHeight(); 
     ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton9); 
     toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       if (isChecked) { 
        for (int i = 0; i < listView.getChildCount(); i++) { 
         double max = 2 * 90; 
         Resources r = getResources(); 
         float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 72, r.getDisplayMetrics()); 
         listView.getChildAt(i).setMinimumHeight((int) px); 
        } 

        // The toggle is enabled 
       } else { 
        // The toggle is disabled 
        for (int i = 0; i < listView.getChildCount(); i++) { 
         listView.getChildAt(i).setMinimumHeight(frth); 
        } 
       } 
      } 
     }); 
     String[] values = new String[1000000]; 
     int temp =0 ; 
     final int PERMISSIONS_REQUEST_READ_CONTACTS = 100; 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { 
      requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS); 
      ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 225); 

      //After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method 
     } else { 

      Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); 
      while (phones.moveToNext()) { 
       String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); 
       values[temp] = name; 
       temp += 1; 

      } 
      phones.close();} 
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.row, R.id.text, values); 
      listView.setAdapter(adapter); 
      // Assign adapter to ListView 
      listView.setAdapter(adapter); 

      // ListView Item Click Listener 
      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

       @Override 
       public void onItemClick(AdapterView<?> parent, View view, 
             int position, long id) { 

        // ListView Clicked item index 
        int itemPosition = position; 

        // ListView Clicked item value 
        String itemValue = (String) listView.getItemAtPosition(position); 

        // Show Alert 
        Toast.makeText(getApplicationContext(), 
          itemValue, Toast.LENGTH_LONG) 
          .show(); 

       } 

      }); 

     } 


} 

私はすでに追加

<uses-permission android:name="android.permission.READ_CONTACTS" /> 

任意のアイデアと私のマニフェストを変更?

編集: 私の新しいMainACtivityが、私の問題はまだそこにある...任意のアイデアですか?

public class MainActivity extends AppCompatActivity { 
    public static final int REQUEST_CODE_ASK_PERMISSIONS = 123; 
    ReadContacts values = new ReadContacts(); 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // Readcontacts val = new Readcontacts(); 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     // Get ListView object from xml 
     // Here, thisActivity is the current activity 
     int permissionCheck = ContextCompat.checkSelfPermission(this, 
       Manifest.permission.READ_CONTACTS); 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.READ_CONTACTS) 
       != PackageManager.PERMISSION_GRANTED) { 

      // Should we show an explanation? 
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
        Manifest.permission.READ_CONTACTS)) { 

       // Show an explanation to the user *asynchronously* -- don't block 
       // this thread waiting for the user's response! After the user 
       // sees the explanation, try again to request the permission. 

      } else { 

       // No explanation needed, we can request the permission. 

       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.READ_CONTACTS}, 
         REQUEST_CODE_ASK_PERMISSIONS); 

       // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an 
       // app-defined int constant. The callback method gets the 
       // result of the request. 
      } 
     } 

/* 

     int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.READ_CONTACTS); 
     if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) { 
      requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 
        REQUEST_CODE_ASK_PERMISSIONS); }*/ 
     final ListView listView = (ListView) findViewById(R.id.list); 
     final int frth = listView.getHeight(); 
     ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton9); 
     toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       if (isChecked) { 
        for (int i = 0; i < listView.getChildCount(); i++) { 
         double max = 2 * 90; 
         Resources r = getResources(); 
         float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 72, r.getDisplayMetrics()); 
         listView.getChildAt(i).setMinimumHeight((int) px); 
        } 

        // The toggle is enabled 
       } else { 
        // The toggle is disabled 
        for (int i = 0; i < listView.getChildCount(); i++) { 
         listView.getChildAt(i).setMinimumHeight(frth); 
        } 
       } 
      } 
     }); 
     String[] values = new String[1000000]; 
     int temp =0 ; 
     //final int PERMISSIONS_REQUEST_READ_CONTACTS = 100; 
     // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { 
     // requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS); 
      // ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 225); 

      //After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method 
     //} else { 

      Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); 
      while (phones.moveToNext()) { 
       String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); 
       values[temp] = name; 
       temp += 1; 

      } 
      phones.close();//} 
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.row, R.id.text, values); 
      listView.setAdapter(adapter); 
      // Assign adapter to ListView 
      listView.setAdapter(adapter); 

      // ListView Item Click Listener 
      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

       @Override 
       public void onItemClick(AdapterView<?> parent, View view, 
             int position, long id) { 

        // ListView Clicked item index 
        int itemPosition = position; 

        // ListView Clicked item value 
        String itemValue = (String) listView.getItemAtPosition(position); 

        // Show Alert 
        Toast.makeText(getApplicationContext(), 
          itemValue, Toast.LENGTH_LONG) 
          .show(); 

       } 

      }); 

     } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, 
              String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case REQUEST_CODE_ASK_PERMISSIONS: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

        // permission was granted, yay! Do the 
        // contacts-related task you need to do. 

       } else { 

        // permission denied, boo! Disable the 
        // functionality that depends on this permission. 
       } 
       return; 
      } 

      // other 'case' lines to check for other 
      // permissions this app might request 
     } 
    } 
} 

エラーは、Android 6.0(APIレベル23)で始まり

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.serepasf.myapp4/com.example.serepasf.myapp4.MainActivity}: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord{c638436 27660:com.example.serepasf.myapp4/u0a756} (pid=27660, uid=10756) requires android.permission.READ_CONTACTS or android.permission.WRITE_CONTACTS 
+0

どの行がでクラッシュです:私が試したhttps://developer.android.com/training/permissions/requesting.html

サンプルコード:

@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_READ_CONTACTS: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // contacts-related task you need to do. } else { // permission denied, boo! Disable the // functionality that depends on this permission. } return; } // other 'case' lines to check for other // permissions this app might request } } 

あなたはまた、公式ドキュメントを確認することができますか?例外は何ですか?エラーログを送信します。 –

+0

クラッシュログを送信します。また、コールバックメソッド 'onRequestPermissionsResult(int、String []、int []) 'の実装が表示されません –

+0

あなたの許可' onRequestPermissionsResult'はどこですか? – MohammedAlSafwan

答えて

0

で、ユーザーはアプリが動作しているときに権限を付与する必要があります。

ステップ-1 あなたは許可がこのコードを実装することによって、マニフェストで宣言されているかどうかを確認する必要があります。

// Assume thisActivity is the current activity 
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, 
     Manifest.permission.WRITE_CALENDAR); 

工程 - 2 あなたはこれらの権限を要求されている理由をユーザーに説明することができます。最後にrequestPermissionsダイアログを表示します。以下のコードを使用してロジックを記述してください。

// Here, thisActivity is the current activity 
if (ContextCompat.checkSelfPermission(thisActivity, 
       Manifest.permission.READ_CONTACTS) 
     != PackageManager.PERMISSION_GRANTED) { 

    // Should we show an explanation? 
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity, 
      Manifest.permission.READ_CONTACTS)) { 

     // Show an explanation to the user *asynchronously* -- don't block 
     // this thread waiting for the user's response! After the user 
     // sees the explanation, try again to request the permission. 

    } else { 

     // No explanation needed, we can request the permission. 

     ActivityCompat.requestPermissions(thisActivity, 
       new String[]{Manifest.permission.READ_CONTACTS}, 
       MY_PERMISSIONS_REQUEST_READ_CONTACTS); 

     // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an 
     // app-defined int constant. The callback method gets the 
     // result of the request. 
    } 
} 

ステップ-3 ユーザーがアプリに許可を与えることができる場所今ダイアログボックスが表示されます。ユーザーの応答は、次のメソッドに渡されます。onRequestPermissionsResult()ここでは、ユーザーが権限を拒否した場合を処理し、この権限を付与しないとアクションを実行できないというダイアログを表示できます。このため、以下のコードを使用します。

package com.karan.permissions; 

import android.Manifest; 
import android.content.ContentResolver; 
import android.content.pm.PackageManager; 
import android.database.Cursor; 
import android.os.Build; 
import android.os.Bundle; 
import android.provider.ContactsContract; 
import android.support.v7.app.AppCompatActivity; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.Toast; 

import java.util.ArrayList; 
import java.util.List; 


/** 
* @author karan 
* @date 20/3/17 
*/ 

public class MainActivity extends AppCompatActivity { 

    // Request code for READ_CONTACTS. It can be any number > 0. 
    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100; 
    // The ListView 
    private ListView name_list; 

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

     // Find the list view 
     this.name_list = (ListView) findViewById(R.id.name_list); 

     // Read and show the contacts 
     showContacts(); 
    } 

    /** 
    * Show the contacts in the ListView. 
    */ 
    private void showContacts() { 
     // Check the SDK version and whether the permission is already granted or not. 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { 
      requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS); 
      //After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method 
     } else { 
      // Android version is lesser than 6.0 or the permission is already granted. 
      List<String> contacts = getContactNames(); 
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contacts); 
      name_list.setAdapter(adapter); 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String[] permissions, 
              int[] grantResults) { 
     if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) { 
      if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
       // Permission is granted 
       showContacts(); 
      } else { 
       Toast.makeText(this, "Until you grant the permission, we canot display the names", Toast.LENGTH_SHORT).show(); 
      } 
     } 
    } 

    /** 
    * Read the name of all the contacts. 
    * 
    * @return a list of names. 
    */ 
    private List<String> getContactNames() { 
     List<String> contacts = new ArrayList<>(); 
     // Get the ContentResolver 
     ContentResolver cr = getContentResolver(); 
     // Get the Cursor of all the contacts 
     Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); 

     // Move the cursor to first. Also check whether the cursor is empty or not. 
     if (cursor.moveToFirst()) { 
      // Iterate through the cursor 
      do { 
       // Get the contacts name 
       String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
       contacts.add(name); 
      } while (cursor.moveToNext()); 
     } 
     // Close the curosor 
     cursor.close(); 

     return contacts; 
    } 
} 
+0

ありがとう、すべて私は私のMainActivityの始めに追加されますか? –

+0

@FilipposSerはいそうすることができます。解決策があなたのために働くなら、答えを受け入れてください。 –

+0

私が言ったように、あなたは同じ結果で上に見ることができるように私の主な活動を読み返しました。 –

関連する問題