Android Studio 學習(六)內容提供器
運行時權限
- 使用ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED//判斷是否有權限
- ActivityCompat.requestPermissions(MainActivity.this,
new String[] {Manifest.permission.CALL_PHONE},1);//沒有權限 進行申請 - onRequestPermissionResult() //無論哪種結果都會回調到這個函數中 所以重寫這個函數
makecallButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(MainActivity.this,
new String[] {Manifest.permission.CALL_PHONE},1);
else
call();
}
});
private void call()
{
try{
Intent intent = new Intent (Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
}
catch (SecurityException e)
{
e.printStackTrace();
}
}
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode){ case 1: if(grantResults.length >0 && grantResults[0]== PackageManager.PERMISSION_GRANTED) call(); else Toast.makeText(MainActivity.this,"you denied the permission",Toast.LENGTH_LONG).show(); break; default: } }
}
查找聯系人姓名和電話
ListView contactsView = (ListView) findViewById(R.id.listview);
adapter = new ArrayAdapter
private void readContanct()
{
Cursor cursor = null;
try{
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,null,null,null);
if(cursor != null)
while (cursor.moveToNext()){
String displayName = cursor.getString(cursor.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number =cursor.getColumnName(cursor.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsList.add(number);
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
if(cursor!=null)
cursor.close();
}
}
Android Studio 學習(六)內容提供器