当前位置:  编程技术>移动开发
本页文章导读:
    ▪怎么使用QuickContactBadge        如何使用QuickContactBadge 参考文章:http://mobile.tutsplus.com/tutorials/android/android-sdk_contact-badge/If you’ve spent any time on an Android device, you may have noticed how you can click on little Contact images to launch a toolba.........
    ▪ QuickContactBadge怎么实现        QuickContactBadge如何实现 从前一篇,我们知道了如何使用了QuikcContactBadge.这一篇我们看QuikcContactBadge是如何实现。开源好处就在于,你可以尽情地了解你想了解。我们都知道QuickContactBadge是从.........
    ▪ Handler惯用一些方法       Handler常用一些方法。 对于Handler我不想说那些理论的机制问题。这里只介绍几种我用到的方法,仅供有需要的朋友参考:Handler与UI界面交互操作,可避免主线程做过多耗时操作引发的问题.........

[1]怎么使用QuickContactBadge
    来源: 互联网  发布时间: 2014-02-18
如何使用QuickContactBadge
参考文章:http://mobile.tutsplus.com/tutorials/android/android-sdk_contact-badge/



If you’ve spent any time on an Android device, you may have noticed how you can click on little Contact images to launch a toolbar with lots of different actions, such as call, text or email that person. In this Quick Tip, you learn how to build this great functionality—called the Quick Contact Badge—into your own applications.
In order to have easy access to contacts, we’ll start with our existing open source code here. We enhance this project, which initially allowed the user to simply choose a contact from a list, and create several different quick contact badges for that contact to illustrate how they work.
Note: This tutorial requires Android 2.0 or higher.
Step 1: Adding an Activity
Start with a new Activity called QuickContactBadgeActivity. Inside the onCreate() method, add a setContentView() method call for a new layout called badge (e.g. R.id.badge).
view plaincopy to clipboardprint?
public class QuickContactBadgeActivity extends Activity { 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
 
        setContentView(R.layout.badge); 
    } 

Step 2: Creating the Layout
Now you need to create a layout using QuickContactBadge controls. The QuickContactBadge control was introduced in Android 2.0 (API Level 5). The following layout creates two QuickContactBadge controls and provides a holder for a third (a FrameLayout control). The QuickContactBadge control is derived from an ImageView control. Thus, you can set the image displayed by the QuickContactBadge control just as you would an ImageView, using the src attribute.
Here’s the final layout we’re using:
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 
    <TextView 
        android:text="Sample Quick Contact Badges" 
        android:id="@+id/TextView01" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content"></TextView> 
    <Button 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@+id/pick_contact" 
        android:onClick="onPickContact" 
        android:text="@string/pick_contact_for_badge"></Button> 
    <QuickContactBadge 
        android:id="@+id/badge_small" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:src="/blog_article/@drawable/droid_small/index.html"></QuickContactBadge> 
    <QuickContactBadge 
        android:id="@+id/badge_medium" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"></QuickContactBadge> 
    <FrameLayout 
        android:id="@+id/badge_holder_large" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"></FrameLayout> 
</LinearLayout> 
QuickContactBadge controls can launch the contact action bar (as we’re calling it) in three different sizes: small, medium (default), and large. The small action bar contains only the action buttons and minimal details. The medium action bar contains the action buttons and some additional contact info. The large action bar contains lots of actions, contact info and graphics.
Note: The current ADT plug-in for Eclipse allows you to set the window size of the contact action bar in XML. An error is shown when you try to set a value, though. Unfortunately, this means you can’t actually set this attribute in the XML layout file. Instead, you must set the window size programmatically using the setMode() method of the QuickContactBadge class. You will see how in the next step.
Step 2: Configuring the Badges
Within the onCreate() method of the Activity, add the following code, replacing the email address with one in your contacts (add it ahead of time if you need to).
view plaincopy to clipboardprint?
QuickContactBadge badgeSmall = (QuickContactBadge) findViewById(R.id.badge_small); 
badgeSmall.assignContactFromEmail("any@gmail.com", true); 
badgeSmall.setMode(ContactsContract.QuickContact.MODE_SMALL); 
The more information that is associated with the contact tied to the badge, the more action items will be available for use in the contact action bar. For instance, here’s one using my own email address:

And here’s another with a contact that has a web address assigned:

You can use the setExcludeMimeTypes() method of the QuickContactBadge class to remove any actions or information you don’t want to display.
Step 3: Working with Unknown Contacts
The previous example worked well because you already knew your own address or added a contact you knew to exist. What if the contact doesn’t yet exist within your Contacts database? Try it!
Add the following code, this time to look up a phone number that you probably don’t have in your address book:
view plaincopy to clipboardprint?
QuickContactBadge badgeMedium = (QuickContactBadge) findViewById(R.id.badge_medium); 
badgeMedium.assignContactFromPhone("831-555-1212", true); 
badgeMedium.setImageResource(R.drawable.droid_small); 
Note also that this time we are using a medium sized QuickContactBadge. When clicking on the QuickContactBadge for an unknown entry, something interesting happens. The user is asked if they want to add the contact. If they choose yes, they’ll get the option to add the email or phone number to an existing contact or create a new contact. Then, on subsequent presses of this QuickContactBadge, the contact will exist and be found. This can be quite handy.

Step 4: Creating a QuickContactBadge From an Existing Contact
Generally speaking, you don’t know what contacts are on someone’s device. You do, however, have access to the Contacts content provider and can retrieve URIs for each contact as needed. You learned how to launch the contact picker in this previous tutorial.
Here’s an example of how we can use a contact URI to supply the contact information for a QuickContactBadge:
view plaincopy to clipboardprint?
public void onPickContact(View view) { 
    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, 
            Contacts.CONTENT_URI); 
    startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT); 

 
@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode == RESULT_OK) { 
        switch (requestCode) { 
        case CONTACT_PICKER_RESULT: 
            Uri contactUri = data.getData(); 
            FrameLayout badgeLargeHolder = (FrameLayout) findViewById(R.id.badge_holder_large); 
 
            QuickContactBadge badgeLarge = new QuickContactBadge(this); 
            badgeLarge.assignContactUri(contactUri); 
            badgeLarge.setMode(ContactsContract.QuickContact.MODE_LARGE); 
            badgeLarge.setImageResource(R.drawable.droid_small); 
            badgeLargeHolder.addView(badgeLarge); 
            break; 
        } 
    } 

Here you use the Contact Uri chosen by the user to configure a QuickContactBadge that the user can click on. In addition, this shows the final, and largest, contact action bar mode.

Using the QuickContactBadge
When might you want to use the QuickContactBadge? Use the QuickContactBadge anywhere that displays friends or lists of contacts, enabling the user to interact with these individuals in other ways. You could also add your email and phone number to the Contacts and provide a QuickContactBadge within your application to give users a quick way to email, call, or message you (or your support team).
Conclusion
In this Quick Tip, you learned how to use the QuickContactBadge control to quickly bring up the contact action bar (available in various sizes) and enable various actions to be taken. The QuickContactBadge is a standard view control available in Android 2.0 and higher, so users should be familiar with its purpose, and therefore appreciate it when developers take advantage of its powerful features. The QuickContactBadge can also save you, the developer, valuable time in creating all of the possible Intent actions that this control provides with ease.

除此之外,还可以看APIDemo-->app->QuickContactsDemo的例子

    
[2] QuickContactBadge怎么实现
    来源: 互联网  发布时间: 2014-02-18
QuickContactBadge如何实现
从前一篇,我们知道了如何使用了QuikcContactBadge.这一篇我们看QuikcContactBadge是如何实现。开源好处就在于,你可以尽情地了解你想了解。
我们都知道QuickContactBadge是从ImageView继承而来的,我们先来看QuikcContactBadge的源码:
framework\base\core\java\android\widget\QuikcContactBadge.java
/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.widget;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Intents;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.QuickContact;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import com.android.internal.R;

/**
 * Widget used to show an image with the standard QuickContact badge
 * and on-click behavior.
 */
public class QuickContactBadge extends ImageView implements OnClickListener {

    private Uri mContactUri;
    private String mContactEmail;
    private String mContactPhone;
    private int mMode;
    private QueryHandler mQueryHandler;
    private Drawable mBadgeBackground;
    private Drawable mNoBadgeBackground;
    private int mSelectedContactsAppTabIndex = -1;

    protected String[] mExcludeMimes = null;

    static final private int TOKEN_EMAIL_LOOKUP = 0;
    static final private int TOKEN_PHONE_LOOKUP = 1;
    static final private int TOKEN_EMAIL_LOOKUP_AND_TRIGGER = 2;
    static final private int TOKEN_PHONE_LOOKUP_AND_TRIGGER = 3;
    static final private int TOKEN_CONTACT_LOOKUP_AND_TRIGGER = 4;

    static final String[] EMAIL_LOOKUP_PROJECTION = new String[] {
        RawContacts.CONTACT_ID,
        Contacts.LOOKUP_KEY,
    };
    static final int EMAIL_ID_COLUMN_INDEX = 0;
    static final int EMAIL_LOOKUP_STRING_COLUMN_INDEX = 1;

    static final String[] PHONE_LOOKUP_PROJECTION = new String[] {
        PhoneLookup._ID,
        PhoneLookup.LOOKUP_KEY,
    };
    static final int PHONE_ID_COLUMN_INDEX = 0;
    static final int PHONE_LOOKUP_STRING_COLUMN_INDEX = 1;

    static final String[] CONTACT_LOOKUP_PROJECTION = new String[] {
        Contacts._ID,
        Contacts.LOOKUP_KEY,
    };
    static final int CONTACT_ID_COLUMN_INDEX = 0;
    static final int CONTACT_LOOKUPKEY_COLUMN_INDEX = 1;


    public QuickContactBadge(Context context) {
        this(context, null);
    }

    public QuickContactBadge(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public QuickContactBadge(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a =
            context.obtainStyledAttributes(attrs,
                    com.android.internal.R.styleable.QuickContactBadge, defStyle, 0);

        mMode = a.getInt(com.android.internal.R.styleable.QuickContactBadge_quickContactWindowSize,
                QuickContact.MODE_MEDIUM);

        a.recycle();

        init();

        mBadgeBackground = getBackground();
    }

    private void init() {
        mQueryHandler = new QueryHandler(mContext.getContentResolver());
        setOnClickListener(this);
    }

    /**
     * Set the QuickContact window mode. Options are {@link QuickContact#MODE_SMALL},
     * {@link QuickContact#MODE_MEDIUM}, {@link QuickContact#MODE_LARGE}.
     * @param size
     */
    public void setMode(int size) {
        mMode = size;
    }

    /**
     * Assign the contact uri that this QuickContactBadge should be associated
     * with. Note that this is only used for displaying the QuickContact window and
     * won't bind the contact's photo for you.
     *
     * @param contactUri Either a {@link Contacts#CONTENT_URI} or
     *            {@link Contacts#CONTENT_LOOKUP_URI} style URI.
     */
    public void assignContactUri(Uri contactUri) {
        mContactUri = contactUri;
        mContactEmail = null;
        mContactPhone = null;
        onContactUriChanged();
    }

    /**
     * Sets the currently selected tab of the Contacts application. If not set, this is -1
     * and therefore does not save a tab selection when a phone call is being made
     * @hide
     */
    public void setSelectedContactsAppTabIndex(int value) {
        mSelectedContactsAppTabIndex = value;
    }

    private void onContactUriChanged() {
        if (mContactUri == null && mContactEmail == null && mContactPhone == null) {
            if (mNoBadgeBackground == null) {
                mNoBadgeBackground = getResources().getDrawable(R.drawable.quickcontact_nobadge);
            }
            setBackgroundDrawable(mNoBadgeBackground);
        } else {
            setBackgroundDrawable(mBadgeBackground);
        }
    }

    /**
     * Assign a contact based on an email address. This should only be used when
     * the contact's URI is not available, as an extra query will have to be
     * performed to lookup the URI based on the email.
     *
     * @param emailAddress The email address of the contact.
     * @param lazyLookup If this is true, the lookup query will not be performed
     * until this view is clicked.
     */
    public void assignContactFromEmail(String emailAddress, boolean lazyLookup) {
        mContactEmail = emailAddress;
        if (!lazyLookup) {
            mQueryHandler.startQuery(TOKEN_EMAIL_LOOKUP, null,
                    Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(mContactEmail)),
                    EMAIL_LOOKUP_PROJECTION, null, null, null);
        } else {
            mContactUri = null;
            onContactUriChanged();
        }
    }

    /**
     * Assign a contact based on a phone number. This should only be used when
     * the contact's URI is not available, as an extra query will have to be
     * performed to lookup the URI based on the phone number.
     *
     * @param phoneNumber The phone number of the contact.
     * @param lazyLookup If this is true, the lookup query will not be performed
     * until this view is clicked.
     */
    public void assignContactFromPhone(String phoneNumber, boolean lazyLookup) {
        mContactPhone = phoneNumber;
        if (!lazyLookup) {
            mQueryHandler.startQuery(TOKEN_PHONE_LOOKUP, null,
                    Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, mContactPhone),
                    PHONE_LOOKUP_PROJECTION, null, null, null);
        } else {
            mContactUri = null;
            onContactUriChanged();
        }
    }

    public void onClick(View v) {
        if (mContactUri != null) {
            mQueryHandler.startQuery(TOKEN_CONTACT_LOOKUP_AND_TRIGGER, null,
                    mContactUri,
                    CONTACT_LOOKUP_PROJECTION, null, null, null);
        } else if (mContactEmail != null) {
            mQueryHandler.startQuery(TOKEN_EMAIL_LOOKUP_AND_TRIGGER, mContactEmail,
                    Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(mContactEmail)),
                    EMAIL_LOOKUP_PROJECTION, null, null, null);
        } else if (mContactPhone != null) {
            mQueryHandler.startQuery(TOKEN_PHONE_LOOKUP_AND_TRIGGER, mContactPhone,
                    Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, mContactPhone),
                    PHONE_LOOKUP_PROJECTION, null, null, null);
        } else {
            // If a contact hasn't been assigned, don't react to click.
            return;
        }
    }

    /**
     * Set a list of specific MIME-types to exclude and not display. For
     * example, this can be used to hide the {@link Contacts#CONTENT_ITEM_TYPE}
     * profile icon.
     */
    public void setExcludeMimes(String[] excludeMimes) {
        mExcludeMimes = excludeMimes;
    }

    private void trigger(Uri lookupUri) {
        final Intent intent = QuickContact.getQuickContactIntent(getContext(), this, lookupUri,
                mMode, mExcludeMimes);
        if (mSelectedContactsAppTabIndex != -1) {
            intent.putExtra(QuickContact.EXTRA_SELECTED_CONTACTS_APP_TAB_INDEX,
                    mSelectedContactsAppTabIndex);
        }
        getContext().startActivity(intent);
    }

    private class QueryHandler extends AsyncQueryHandler {

        public QueryHandler(ContentResolver cr) {
            super(cr);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            Uri lookupUri = null;
            Uri createUri = null;
            boolean trigger = false;

            try {
                switch(token) {
                    case TOKEN_PHONE_LOOKUP_AND_TRIGGER:
                        trigger = true;
                        createUri = Uri.fromParts("tel", (String)cookie, null);

                        //$FALL-THROUGH$
                    case TOKEN_PHONE_LOOKUP: {
                        if (cursor != null && cursor.moveToFirst()) {
                            long contactId = cursor.getLong(PHONE_ID_COLUMN_INDEX);
                            String lookupKey = cursor.getString(PHONE_LOOKUP_STRING_COLUMN_INDEX);
                            lookupUri = Contacts.getLookupUri(contactId, lookupKey);
                        }

                        break;
                    }
                    case TOKEN_EMAIL_LOOKUP_AND_TRIGGER:
                        trigger = true;
                        createUri = Uri.fromParts("mailto", (String)cookie, null);

                        //$FALL-THROUGH$
                    case TOKEN_EMAIL_LOOKUP: {
                        if (cursor != null && cursor.moveToFirst()) {
                            long contactId = cursor.getLong(EMAIL_ID_COLUMN_INDEX);
                            String lookupKey = cursor.getString(EMAIL_LOOKUP_STRING_COLUMN_INDEX);
                            lookupUri = Contacts.getLookupUri(contactId, lookupKey);
                        }
                        break;
                    }

                    case TOKEN_CONTACT_LOOKUP_AND_TRIGGER: {
                        if (cursor != null && cursor.moveToFirst()) {
                            long contactId = cursor.getLong(CONTACT_ID_COLUMN_INDEX);
                            String lookupKey = cursor.getString(CONTACT_LOOKUPKEY_COLUMN_INDEX);
                            lookupUri = Contacts.getLookupUri(contactId, lookupKey);
                            trigger = true;
                        }

                        break;
                    }
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }

            mContactUri = lookupUri;
            onContactUriChanged();

            if (trigger && lookupUri != null) {
                // Found contact, so trigger track
                trigger(lookupUri);
            } else if (createUri != null) {
                // Prompt user to add this person to contacts
                final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, createUri);
                getContext().startActivity(intent);
            }
        }
    }
}

从source code我们可以知道QuickContactBadge已经处理了它的onClick事件。通过AsyncQueryHandler(用这个来查询的好处待会稍后研究^_^)来异步查询Contact的信息,进而做出了不同的处理,// Found contact, so trigger track
                trigger(lookupUri);若查询到了已经有这样的Contact就会发出com.android.contacts.action.QUICK_CONTACT这样的Intent去启动我们看到的Contact tools:call.message,web...而处理这个Intent的Acticity是位于Contact里面的QuickContactActivity.java(大家可以在这里继续研究Contact tools的UI是怎么形成与实现的)。那还有另外一种情况就是这个Contact还没有保存在手机里,那么就会
inal Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, createUri);
                getContext().startActivity(intent);启动是否要保存这个contact的Activity.发出com.android.contacts.action.SHOW_OR_CREATE_CONTACT这个Intent,而处理这个Activity也是在Contact这个源码里面的ShowOrCreateActivity。




1 楼 bingtao115 2011-12-02  
源码引用的太多了,关键的东西说的太少

    
[3] Handler惯用一些方法
    来源: 互联网  发布时间: 2014-02-18
Handler常用一些方法。
对于Handler我不想说那些理论的机制问题。这里只介绍几种我用到的方法,仅供有需要的朋友参考:Handler与UI界面交互操作,可避免主线程做过多耗时操作引发的问题。
1)按计划发送消息或执行某个Runnanble(使用POST方法);
2)从其他线程中发送来的消息放入消息队列中,避免线程冲突(常见于更新UI线程)
接收消息:Handler handler = new Handler(){
            public void handleMessage(Message msg) { 
               switch (msg.what) { 
                case UPDATA_WAT: 
                   updataView(); 
                 break; 
                }  }; };
发送消息:post(Runnable) postAtTime(Runnable,long)
         postDelayed(Runnable,long)sendEmptyMessage(int)
         sendMessage(Message) sendMessageAtTime(Message,long)
         sendMessageDelayed(Message,long)

      1) Message msg = new Message();
         msg.wat = UPDATA_WAT;
         handler.sendMessage(msg);
      2) Message msg = handler.obtainMessage(UPDATA_WAT);可添加其他参数
          handler.sendMessage(msg);
传递数据:Message msg = handler.obtainMessage();
          Bundle b = new Bundle();
          b.putInt("age", 20);
          b.putString("name", "Lily");
          msg.setData(b);
          msg.sendToTarget();
                        public void handleMessage(Message msg) {
                            Bundle b = msg.getData();
                            int age = b.getInt("age");
                            String name = b.getString("name");
未完待续……

    
最新技术文章:
▪Android开发之登录验证实例教程
▪Android开发之注册登录方法示例
▪Android获取手机SIM卡运营商信息的方法
▪Android实现将已发送的短信写入短信数据库的...
▪Android发送短信功能代码
▪Android根据电话号码获得联系人头像实例代码
▪Android中GPS定位的用法实例
▪Android实现退出时关闭所有Activity的方法
▪Android实现文件的分割和组装
▪Android录音应用实例教程
▪Android双击返回键退出程序的实现方法
▪Android实现侦听电池状态显示、电量及充电动...
▪Android获取当前已连接的wifi信号强度的方法
▪Android实现动态显示或隐藏密码输入框的内容
▪根据USER-AGENT判断手机类型并跳转到相应的app...
▪Android Touch事件分发过程详解
▪Android中实现为TextView添加多个可点击的文本
▪Android程序设计之AIDL实例详解
oracle iis7站长之家
▪Android按钮单击事件的四种常用写法总结
▪Android消息处理机制Looper和Handler详解
▪Android实现Back功能代码片段总结
▪Android实用的代码片段 常用代码总结
▪Android实现弹出键盘的方法
▪Android中通过view方式获取当前Activity的屏幕截...
▪Android提高之自定义Menu(TabMenu)实现方法
▪Android提高之多方向抽屉实现方法
▪Android提高之MediaPlayer播放网络音频的实现方法...
▪Android提高之MediaPlayer播放网络视频的实现方法...
▪Android提高之手游转电视游戏的模拟操控
 


站内导航:


特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

©2012-2021,,E-mail:www_#163.com(请将#改为@)

浙ICP备11055608号-3