Activity 在调用运行时权限时变黑

Posted

技术标签:

【中文标题】Activity 在调用运行时权限时变黑【英文标题】:Activity becomes black while calling the run time permissions 【发布时间】:2016-11-28 12:25:12 【问题描述】:

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

    

    


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

没有弄错。

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

【问题讨论】:

【参考方案1】:

确保您没有在androidMenifest.xml 的活动声明中输入android:noHistory=true 属性。

【讨论】:

哦,是的.. 但我希望此活动不保留任何历史记录。 @Keval Patel 您可以在离开活动或开始新活动的任何地方呼叫finish()(使用startActivity()startActivityForResult())。这将从后台堆栈中删除您的活动。【参考方案2】:

替换requestPermissions(new String[]Manifest.permission.READ_CONTACTS, PERMISSIONS_REQUEST_READ_CONTACTS);

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

【讨论】:

以上是关于Activity 在调用运行时权限时变黑的主要内容,如果未能解决你的问题,请参考以下文章

当我们有多个活动时如何集中运行时权限

在其他应用中启动另一个 Activity 时需要帮助修复权限错误

运行时权限

Appium运行时没有启动activity的权限:A new session could not be created.(Original error: Permission to start act

Android 6.0+ 运行时权限

即使在运行 GRANT ALL to role 之后,使用 SECURITY DEFINER 调用函数时权限被拒绝