Android編程實現讀取手機連絡人、撥號、傳送簡訊及長按菜單操作方法執行個體小結_Android

來源:互聯網
上載者:User

本文執行個體講述了Android編程實現讀取手機連絡人、撥號、傳送簡訊及長按菜單操作方法。分享給大家供大家參考,具體如下:

1.Andrid項目結構圖↓主要操作圖中紅色方框內的檔案。

2.首先布局代碼如下

a, main.xml 程式啟動並執行主介面,主要用ListView清單控制項展示手機連絡人

<?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:background="@drawable/bg"android:orientation="vertical" ><ListViewandroid:id="@+id/listView"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_marginLeft="5dip"android:cacheColorHint="#00000000"android:divider="@drawable/divider_horizontal_bright"android:paddingRight="5dip" ></ListView></LinearLayout>

b.list_item.xml ListView的清單項目布局檔案,相當於展示模版

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal" ><ImageViewandroid:id="@+id/imgView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:contentDescription="@string/photo"android:paddingRight="2dip" /><TextViewandroid:id="@+id/name"android:layout_width="80dip"android:layout_height="wrap_content"android:layout_marginLeft="10dip"android:paddingTop="8dip"android:singleLine="false"android:textAppearance="?android:attr/textAppearanceMedium"android:textColor="#ffffff" /><TextViewandroid:id="@+id/number"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginRight="6dip"android:paddingTop="8dip"android:singleLine="false"android:textColor="#ffffff"android:textAppearance="?android:attr/textAppearanceMedium"/></LinearLayout>

c,phonedetails.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="vertical" ><TextViewandroid:id="@+id/ymw"android:layout_width="fill_parent"android:layout_height="wrap_content"android:textAppearance="?android:attr/textAppearanceMedium"/></LinearLayout>

2.Java實現代碼如下

a,MainActivity.java 程式啟動並執行入口檔案

package com.example.myandroid;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import android.app.Activity;import android.content.ContentResolver;import android.content.Intent;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.provider.ContactsContract;import android.provider.ContactsContract.CommonDataKinds;import android.view.ContextMenu;import android.view.ContextMenu.ContextMenuInfo;import android.view.MenuItem;import android.view.View;import android.view.View.OnCreateContextMenuListener;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;import com.ymw.details.Detail;public class MainActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);final ListView listView = (ListView) findViewById(R.id.listView);// 產生動態數組,加入資料ArrayList<HashMap<String, Object>> listItem = fillMaps();SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,R.layout.list_item,new String[] { "imgView", "name", "number" }, new int[] {R.id.imgView, R.id.name, R.id.number });listView.setAdapter(listItemAdapter);// 添加單擊事件listView.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(arg2);String name = map.get("name");Toast toast = Toast.makeText(getApplicationContext(), "第"+ arg2 + "項" + name, Toast.LENGTH_LONG);toast.show();String phoneNum = map.get("number");Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ phoneNum));startActivity(intent);}});// 添加長按菜單listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {menu.setHeaderTitle("長按菜單-ContextMenu");menu.add(0, 0, 0, "查看詳細");menu.add(0, 1, 0, "發送資訊");menu.add(0, 2, 0, "刪除連絡人");}});}public boolean onContextItemSelected(MenuItem item) {// setTitle("點擊了長按菜單裡面的第"+item.getItemId()+"個項目");Toast.makeText(getApplicationContext(),"選擇了" + item.getItemId() + item.getTitle() + "項",Toast.LENGTH_LONG).show();int id = item.getItemId();// 查看詳細if (id == 0) {Intent intent = new Intent();intent.putExtra("ymw", item.getTitle());intent.setClass(MainActivity.this, Detail.class);startActivity(intent);}// 傳送簡訊else if (id == 1) {Uri uri = Uri.parse("smsto://18664599745");Intent intent = new Intent(Intent.ACTION_SENDTO, uri);intent.putExtra("sms_body", "ymw-LOVE-yh");startActivity(intent);}// 刪除連絡人else if (id == 2) {}return super.onContextItemSelected(item);}// 擷取手機連絡人清單方法一public ArrayList<HashMap<String, Object>> GetContects() {ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null,null,ContactsContract.Contacts.DISPLAY_NAME+ " COLLATE LOCALIZED ASC");if (cursor.moveToFirst()) {int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);int nameColum = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);do {String contactId = cursor.getString(idColumn);String disPlayNameString = cursor.getString(nameColum);// 查看有多少電話號碼 沒有則返回為0int phoneCount = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));if (phoneCount > 0) {// 獲得連絡人的電話號碼Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ "=" + contactId, null, null);HashMap<String, Object> map = new HashMap<String, Object>();map.put("imgView", R.drawable.ic_launcher);map.put("name", disPlayNameString);list.add(map);}} while (cursor.moveToNext());if (cursor != null)cursor.close();}return list;}// 擷取連絡人方法二public ArrayList<HashMap<String, Object>> fillMaps() {ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();ContentResolver cr = getContentResolver();HashMap<String, ArrayList<String>> hashMap = new HashMap<String, ArrayList<String>>();Cursor phone = cr.query(CommonDataKinds.Phone.CONTENT_URI,new String[] { CommonDataKinds.Phone.CONTACT_ID,CommonDataKinds.Phone.DISPLAY_NAME,CommonDataKinds.Phone.NUMBER,CommonDataKinds.Phone.DATA1// CommonDataKinds.StructuredPostal.DATA3,}, null, null, null);while (phone.moveToNext()) {String contactId = phone.getString(phone.getColumnIndex(CommonDataKinds.Phone.CONTACT_ID));String displayName = phone.getString(phone.getColumnIndex(CommonDataKinds.Phone.DISPLAY_NAME));String PhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));String address = phone.getString(phone.getColumnIndex(CommonDataKinds.Phone.DATA1));// 以contactId為主鍵,把同一人的所有電話都存到一起。ArrayList<String> ad = hashMap.get(contactId);if (ad == null) {ad = new ArrayList<String>();ad.add(displayName);ad.add(PhoneNumber);// ad.add(address);hashMap.put(contactId, ad);} else {ad.add(PhoneNumber);}}phone.close();ArrayList<String> tmpList;String tmpStr = "";int k;Iterator iter = hashMap.entrySet().iterator();while (iter.hasNext()) {HashMap.Entry entry = (HashMap.Entry) iter.next();Object key = entry.getKey();Object val = entry.getValue();tmpList = (ArrayList) val;tmpStr = "";for (k = 1; k < tmpList.size(); k++) {tmpStr = tmpStr + tmpList.get(k) + ',';}tmpStr = GetString(tmpStr);HashMap<String, Object> tmpMap = new HashMap<String, Object>();tmpMap.put("name", tmpList.get(0));tmpMap.put("number", tmpStr);tmpMap.put("imgView", R.drawable.ic_launcher);items.add(tmpMap);}return items;}private String GetString(String str) {String strLast = "";int i = str.lastIndexOf(",");if (i > 0) {strLast = str.substring(0, str.length() - 1);}return strLast.replace(" ", "").replace(",", "\n").replace("+86", "");}}

b,Detail.java 主介面長按菜單顯示連絡人詳細的跳轉介面,接受主介面傳來的參數

package com.ymw.details;import com.example.myandroid.R;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.widget.TextView;public class Detail extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(com.example.myandroid.R.layout.phonedetails);Intent intent = getIntent();String strPara = intent.getStringExtra("ymw");TextView tView = (TextView) findViewById(R.id.ymw);tView.setText(strPara);}}

3.擷取手機連絡人和撥號發簡訊等需要配置許可權

在AndroidManifest.xml檔案中的application節點上加入如下代碼

<!--添加許可權--><uses-permission android:name="android.permission.SEND_SMS"/><uses-permission android:name="android.permission.CALL_PHONE"/><uses-permission android:name="android.permission.READ_CONTACTS"/>

4.使用Android模擬器或串連Android智能手機運行本程式可以看到手機連絡人清單,

單擊某個連絡人會直接撥號,長按某個連絡人會出現菜單選項,可以選擇傳送簡訊。

希望本文所述對大家Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.