[sms] 03_短信内容搜索1-Search-搜索

Android 4.0

短信搜索-Search-搜索

看文档: User Interface→Search
步骤:



一、创建一个searchable.xml文件()

①必须位于res/xml/下
②必须被<searchable>包含
③必须要有android:label属性,且必须是指向string.xml文件中的资源
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_label"
    android:hint="@string/search_hint" >
</searchable>

二、创建一个Activity,用于展示搜索的结果
①创建Activity
②清单文件配置:
<!-- 搜索UI配置 -->
<activity android:name=".SearchableUI" >
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>
    <meta-data
        android:name="android.app.searchable"
        android:resource="@xml/searchable" />
</activity>
③这个只有当前SearchableUI才能使用搜索,如果要让整个应用都可以用,那么将<meta-data>配置在<application>应用中
三、调用出来搜索对话框
①在特定的Activity中才能调用搜索对话框
<activity android:name="cn.zengfansheng.sms.ConversationUI" >
    <meta-data
        android:name="android.app.default_searchable"
        android:value=".SearchableUI" />
</activity>
②在整个应用中调用搜索对话框
<application
        ......
    <meta-data
        android:name="android.app.default_searchable"
        android:value=".SearchableUI" />
         ......
</application>
③调用onSearchRequested()进行搜索
结果:

1、接收搜索关键字——Receiving the query
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitle("搜索结果");

    Intent intent = getIntent();
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
               // 获取搜索关键字
        String query = intent.getStringExtra(SearchManager.QUERY);
        doMySearch(query);
    }
}
2、开始搜索数据——Searching your data
搜索是一个很耗时的操作,所以用异步查询(AsyncQueryHandler
AsyncQueryHandler

3、展示搜索到的结果(可以用个ListActivity)——Presenting the results
CursorAdapter

结果:


完整代码:
package cn.zengfansheng.sms;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cn.zengfansheng.sms.utils.Sms;
import cn.zengfansheng.sms.utils.Utils;
/**
 * 搜索UI
 * 
 * @author hacket
 * 
 */
public class SearchableUI extends ListActivity {
    private final String[] SEARCH_PROJECTION = { "_id""address""date","body" };
    private final int ADDRESS_COLUMN_INDEX = 1;
    private final int DATE_COLUMN_INDEX = 2;
    private final int BODY_COLUMN_INDEX = 3;
    private SearchAdapter mAdapter;
    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("搜索结果");
        initListView();
        
        // 获取搜索关键字
        Intent intent = getIntent();
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            startQuerySms(query);
        }
    }
    // NOTES================2、异步查询数据AsyncQueryHandler===============
    /**
     * 搜索
     * @param query
     */
    private void startQuerySms(String query) {
        
        SearchAsyncQueryHandler asyncQuery = new SearchAsyncQueryHandler(getContentResolver());
        String selection = "body like ?";
        String[] selectionArgs = { "%" + query + "%" };
        // 异步查询
        asyncQuery.startQuery(0, null, Sms.SMS_URISEARCH_PROJECTION, selection, selectionArgs, "date desc");
        
    }
    class SearchAsyncQueryHandler extends AsyncQueryHandler {
        public SearchAsyncQueryHandler(ContentResolver cr) {
            super(cr);
        }
        
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            mAdapter.changeCursor(cursor);
        }
    }
    // NOTES=================1、设置ListView以及CursorAdapter===============
    private void initListView() {
        listView = getListView();
        mAdapter = new SearchAdapter(thisnulltrue);
        listView.setAdapter(mAdapter);
    }
    class SearchAdapter extends CursorAdapter {
        
        SearchViewHolder mViewHolder;
        long todayStartMillis;
        public SearchAdapter(Context context, Cursor c, boolean autoQuery) {
            super(context, c, autoQuery);
            todayStartMillis = Utils.getTodayStartMillis();
        }
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View view = getLayoutInflater().inflate(R.layout.item_conversation_itemnull);
            mViewHolder = new SearchViewHolder();
            mViewHolder.ivIcon = (ImageView) view.findViewById(R.id.iv_conversation_item_icon);
            mViewHolder.tvName = (TextView) view.findViewById(R.id.tv_conversation_item_name);
            mViewHolder.tvDate = (TextView) view.findViewById(R.id.tv_conversation_item_date);
            mViewHolder.tvBody = (TextView) view.findViewById(R.id.tv_conversation_item_body);
            view.setTag(mViewHolder);
            return view;
        }
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            mViewHolder = (SearchViewHolder) view.getTag();
            
            String address = cursor.getString(ADDRESS_COLUMN_INDEX);
            long date = cursor.getLong(DATE_COLUMN_INDEX);
            String body = cursor.getString(BODY_COLUMN_INDEX);
            mViewHolder.tvBody.setText(body);
            String contactName = Utils.getContactName(getContentResolver(), address);
            if(contactName != null && !"".equals(contactName)) {
                mViewHolder.ivIcon.setBackgroundResource(R.drawable.ic_contact_picture);
                mViewHolder.tvName.setText(contactName);
            } else {
                mViewHolder.ivIcon.setBackgroundResource(R.drawable.ic_unknow_contact_picture);
                mViewHolder.tvName.setText(address);
            }
            
            long diffMillis = date - todayStartMillis;
            if(diffMillis > 0 && diffMillis < DateUtils.DAY_IN_MILLIS) {
                mViewHolder.tvDate.setText(DateFormat.getTimeFormat(SearchableUI.this).format(date));
            } else {
                mViewHolder.tvDate.setText(DateFormat.getDateFormat(SearchableUI.this).format(date));
            }
        }
        
    }
    
    class SearchViewHolder {
        ImageView ivIcon;
        TextView tvName;
        TextView tvDate;
        TextView tvBody;
    }
}