android 电话号码的获取及拨打电话

时间:2022-11-10 10:23:51


在Java

public class MainActivity extends Activity {
 ListView listView;
 ContentResolver content;
 private static final String[] PHONES_PROJECTION=new String[]{
  Phone.DISPLAY_NAME,Phone.NUMBER,Photo.PHOTO_ID,Phone.CONTACT_ID
 };
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  setContentView(R.layout.activity_main);
  listView=(ListView)findViewById(R.id.list);
  content=getContentResolver();
  //获取手机的信息
  Cursor cursor=content.query(Phone.CONTENT_URI, null, null, null, null);
  SimpleCursorAdapter simpleCursorAdapter=new SimpleCursorAdapter(MainActivity.this, R.layout.listitem, cursor, new String[]{Phone.DISPLAY_NAME,Phone.NUMBER}, new int[]{R.id.textname,R.id.textnumber}, 0);
  listView.setAdapter(simpleCursorAdapter);
  //打电话
  listView.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> arg0, View view, int position,
     long arg3) {
   TextView textView=(TextView)view.findViewById(R.id.textnumber);
   Intent intent=new Intent();
   intent.setAction(Intent.ACTION_DIAL);
   intent.setData(Uri.parse("tel:"+textView.getText().toString()));
   startActivity(intent);
    
   }
   
  });
  
  
  
 }

在activity_main 文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.contentprovider.MainActivity" >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
       />

</RelativeLayout>

在创建listitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
 
    <TextView
        android:id="@+id/textname"
        android:layout_width="wrap_content"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="hh"/>
 <TextView
        android:id="@+id/textnumber"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hh"/>
</LinearLayout>