傻啦吧唧的程序员丶

android 分享或者调用系统或者其他app时 应注意! startActivityForResult() 使用

//判断是否有相应的Activity来接受intent
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
boolean isIntentSafe = activities.size() > 0;
如果 isIntentSafe 为true 则有相应的Activity来接受 反之则无。

//始终弹出dialog让用户选择
Intent chooser = Intent.createChooser(intent, "请选择");
始终让用户选择使用什么App打开

判断启动:
if (isIntentSafe){
startActivity(chooser);
}

跳转很简单:
//跳转到通讯录
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
然后启动:
startActivityForResult(pickContactIntent ,1); //传一个1过去,当在返回的时候看是否返回成功的关键


在Acitivity中实现:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1){
if (resultCode == -1){//返回结果的code是-1则成功,0则是空
Uri uri = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(uri, projection,null,null,null);
cursor.moveToFirst();
int column1 = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int column2 = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String number = cursor.getString(column1);
String name = cursor.getString(column2);
Log.i("CCCCCCCCCCCCCCC",number);
Log.i("NNNNNNNNNNNNNNN",name);
}
}
}


posted on 2016-03-21 15:24  傻啦吧唧的程序员丶  阅读(1129)  评论(0编辑  收藏  举报

导航