0

我想调用运行时权限以在单击某些视图时读取联系人。所以我检查应用程序是否有权限,如果没有请求权限。但是,当请求对话框出现时,如果单击对话框上的允许或拒绝,活动将变黑并完成。当我调试应用程序时,单击允许或拒绝后它不会转到 onRequestPermissionsResult 方法。

如果权限被接受,我也会打电话给联系人 Intent。我想在与选定联系人列表相同的活动中显示这些。因此,为此我有一个列表并将联系人添加到列表 onActivitResult 方法中。

但是为此,如果我从联系人中选择一些联系人,活动就会完成。它不会转到 onActivityResult 方法。

public class PlanEventActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener,
        DatePickerDialog.OnDateSetListener {

    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    private boolean mHoursMode, updateEvent, subevent,permissionsAccepted;
    RelativeLayout chooseEvent, time, date;
    EditText eventName, chooseEventText, timeTextView, dateTextView;
    private RelativeLayout parent;
    static final int CUSTOM_DIALOG_ID = 0;
    private String mEventId, mMainEventId;
    ListView dialog_ListView;
    private Intent mIntent;
    private SharedPreferences sharedPreferences;
    private TextView title;
    private ImageView addOrganizer;
    private ArrayList<Organizers> mSelectedContacts;
    private RecyclerViewAdapter mAdapter;
    private RecyclerView mContactsList;
    private ArrayList<Event> subEventArrayList;
    public static final String MyPREFERENCES = "MyPrefs1";
    private Button mSubmit;
    private String mEventType, mEventName, mEventDate, mEventTime, mOraganizerName, mOrganizerPhone,
            mOrganizersId, mOrganizersEmail, mOrganizersLastName, mOrganizerFirstName, userName;
    private Event mEvent;
    private static final int RESULT_PICK_CONTACT = 10;
    private Organizers mOrganizers;
    private ImageButton add;

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

        mIntent = getIntent();

        subEventArrayList = new ArrayList<>();

        setUpUI();

        mContactsList.setLayoutManager(new LinearLayoutManager(this));

        mAdapter = new RecyclerViewAdapter(this, mSelectedContacts);
        mContactsList.setAdapter(mAdapter);
        ((RecyclerViewAdapter) mAdapter).setMode(Attributes.Mode.Single);


    }

    public void setUpUI() {

        addOrganizer = (ImageView) findViewById(R.id.addOrganizer);

        mContactsList = (RecyclerView) findViewById(R.id.selectedContactsList);

        mSubmit = (Button) findViewById(R.id.submit);

        add = (ImageButton) findViewById(R.id.addButton);

        mSelectedContacts = new ArrayList<>();

        updateEvent = mIntent.getBooleanExtra("updateEvent", false);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

                permissionsAccepted = sharedPreferences.getBoolean("permission1",false);

                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 if (permissionsAccepted && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                    startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
                }
                else {

                    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                    startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);

                }
            }
        });

        addOrganizer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

                permissionsAccepted = sharedPreferences.getBoolean("permission1",false);


                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {

                    Log.d("request","Request permission is called");

                    requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);

                }
                else if (permissionsAccepted && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                    startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
                }
                else {

                    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                    startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);

                }

            }
        });

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        String date = dayOfMonth + "/" + (++monthOfYear) + "/" + year;
        dateTextView.setText(date);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {

        if(requestCode == PERMISSIONS_REQUEST_READ_CONTACTS)
        {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // If request is cancelled, the result arrays are empty.

                permissionsAccepted = true;

                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean("permission1", permissionsAccepted);
                editor.commit();


                Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);

            }

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // check whether the result is ok
        if (resultCode == RESULT_OK) {
            // Check for the request code, we might be usign multiple startActivityForReslut
            switch (requestCode) {
                case RESULT_PICK_CONTACT:

                    mOrganizers = new Organizers();
                    contactPicked(data);
                    mOrganizers.setFName(mOrganizerFirstName);
                    mOrganizers.setMobile(mOrganizerPhone);
                    mOrganizers.setEmail(mOrganizersEmail);
                    mOrganizers.setId(mOrganizersId);
                    mOrganizers.setLName(mOrganizersLastName);

                    mSelectedContacts.add(mOrganizers);

                    mAdapter.notifyDataSetChanged();

                    if (mSelectedContacts.size() != 0) {

                        addOrganizer.setVisibility(View.INVISIBLE);
                        mContactsList.setVisibility(View.VISIBLE);
                        add.setVisibility(View.VISIBLE);
                    } else {

                        addOrganizer.setVisibility(View.VISIBLE);

                    }
                    break;
            }
        } else {
            Log.e("MainActivity", "Failed to pick contact");
        }
    }

    private void contactPicked(Intent data) {
        Cursor cursor = null;
        try {

            // getData() method will have the Content Uri of the selected contact
            Uri uri = data.getData();
            //Query the content uri
            cursor = getContentResolver().query(uri, null, null, null, null);
            cursor.moveToFirst();
            // column index of the phone number
            int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            // column index of the contact name
            int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);

            int contactIdIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);

            mOrganizerPhone = cursor.getString(phoneIndex);
            mOraganizerName = cursor.getString(nameIndex);
            mOrganizersId = cursor.getString(contactIdIndex);

            final String[] projection = new String[]{ContactsContract.CommonDataKinds.Email.DATA, // use
                    // Email.ADDRESS
                    // for API-Level
                    // 11+
                    ContactsContract.CommonDataKinds.Email.TYPE};

            Cursor emailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, projection,
                    ContactsContract.Data.CONTACT_ID + "=?", new String[]{String.valueOf(mOrganizersId)}, null);

            if (emailCursor.moveToFirst()) {
                final int contactEmailColumnIndex = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);

                while (!emailCursor.isAfterLast()) {
                    mOrganizersEmail = emailCursor.getString(contactEmailColumnIndex) + ";";
                    emailCursor.moveToNext();
                }
            }

            String[] parts = mOraganizerName.split(" ", 2);
            mOrganizerFirstName = parts[0]; // 004
            mOrganizersLastName = parts[1];

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void resetOrganizer(Context context) {

        addOrganizer.setVisibility(View.VISIBLE);
        mContactsList.setVisibility(View.GONE);

    }

    @Override
    public void onResume() {
        super.onResume();

    }

    public void showAlert(String alert,PlanEventActivity activity) {

        parent = (RelativeLayout)activity.findViewById(R.id.parentPanel);

        Snackbar snackbar = Snackbar.make(parent, alert, Snackbar.LENGTH_LONG);
        snackbar.show();

    }

    }

}

奇怪的是,相同的代码以前可以正常工作。对于旧版本。我也尝试将旧版本的相同活动复制到新版本,但它仍然不起作用。

不明白怎么回事。

有人可以帮忙吗?谢谢..

4

2 回答 2

0

代替requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);

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

于 2016-07-25T08:39:44.810 回答
0

确保您没有android:noHistory=trueAndroidMenifest.xml.

于 2016-07-25T09:06:11.800 回答