安卓分享功能的实现

今天自己做APP的时候,有一个模块是文章中心,里边有很多热文,于是我就想到了如今非常实用的分享功能,可以讲图文啊,视频啊,音乐啊分享到QQ、微信、朋友圈等,于是我也想做一个分享功能,废话不多说,下边跟大家分享我的实现过程。(PS:小弟刚学某卓,望大神指点!)

到目前我刚写完分享到QQ的实现,所以先说说分享到QQ的过程:
1、首先看下效果图吧,点击分享按钮
安卓分享功能的实现_第1张图片 安卓分享功能的实现_第2张图片

弹出选择框,再点击QQ图标,跳转到手机上已经安装的QQ页面
安卓分享功能的实现_第3张图片

随便选择一个分享地点,也可以分享到QQ空间,我们选个   兼职
就会将你自己手机上的内容和图片提取出来,也可以添加评论,点击发送后
安卓分享功能的实现_第4张图片

到底为止,分享成功,你可以选择留在QQ,也可以返回你的应用。

2、其实很简单,想做这部分功能的童鞋可以自己试一试,下边我要说一下具体的制作过程啦
从头开始,那就先从分享按钮的点击事件开始说起吧,上代码:
 
   // 按钮点击事件
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_back:
            finish();
            break;
        //分享按钮点击事件
        case R.id.iv_share:
            Intent intent = new Intent();
            intent.setClass(articleDetailActivity, ShareActivity.class);
            intent.putExtra("title", title);
            intent.putExtra("content", content);
            intent.putExtra("picture", picture);
            startActivity(intent);
            break;
        default:
            break;
        }
    }
//用完Tentent类后销毁以释放资源,否则会出错
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (MainActivity.mTencent != null) {
            MainActivity.mTencent.releaseResource();
        }
    }
我在这里是打开了一个Activity,将我自己文章的内容和标题传进去,下边是分享Activity的具体内容,写的比较乱,大家耐心看:
ShareActivity:


package com.dictionary.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.dictionary.app.ExitApplication;
import com.dictionary.widget.ThreadManager;
import com.example.dictionary.R;
import com.tencent.connect.share.QQShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ShareActivity extends Activity implements AdapterView.OnItemClickListener {

    private LinearLayout mLayout;//布局
    private ShareActivity shareActivity;
    private Context context;
    private int mScreenOrientation;//屏幕的方向
    private GridView mGridView;
    private float mDensity;
    private String msgTitle;// 文章标题
    private String msgText;// 文章内容
    private String mImgPath;// 图片路径
    private List<ShareItem> mListData;//存放分享条目的List
    private Handler mHandler = new Handler();
    // 设置页面横竖屏显示
    private Runnable work = new Runnable() {
        public void run() {
            int orient = getScreenOrientation();
            if (orient != mScreenOrientation) {
                if (orient == 0)
                    mGridView.setNumColumns(4);
                else {
                    mGridView.setNumColumns(6);
                }
                mScreenOrientation = orient;
                ((ShareActivity.MyAdapter) mGridView.getAdapter()).notifyDataSetChanged();
            }
            mHandler.postDelayed(this, 1000L);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        ExitApplication.getInstance().addActivity(this);
        //隐藏软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        context = this.getApplicationContext();
        //初始化布局
        init(context);
        setContentView(this.mLayout);
        getWindow().setGravity(8);
        shareActivity = this;

        if (getScreenOrientation() == 0) {
            this.mScreenOrientation = 0;
            this.mGridView.setNumColumns(4);
        } else {
            this.mGridView.setNumColumns(6);
            this.mScreenOrientation = 1;
        }
        this.mGridView.setAdapter(new MyAdapter());
        this.mGridView.setOnItemClickListener(this);
        this.mHandler.postDelayed(this.work, 1000L);

    }

    //分享条目点击事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // TODO Auto-generated method stub
        ShareItem share = (ShareItem) this.mListData.get(position);
        shareMsg(context, "分享到...", this.msgText, this.mImgPath, share);
    }

    //分享实现方法
    private void shareMsg(Context context, String msgTitle, String msgText, String imgPath, ShareItem share) {
        //如果没有安装此应用
        if (!share.packageName.isEmpty() && !isAvilible(context, share.packageName)) {
            Toast.makeText(context, "请先安装" + share.title, Toast.LENGTH_SHORT).show();
            return;
        }
        // 分享到QQ绑定的参数
        final Bundle params = new Bundle();
        if (share.packageName.equals("com.tencent.mobileqq")) {
            if ((imgPath == null) || (imgPath.equals(""))) {
                // 如果没有图片
            } else {
                // 有图片时
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgPath);//图片路径
            }
            params.putString(QQShare.SHARE_TO_QQ_TITLE, msgTitle);//标题
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, msgText.substring(0, 20));//摘要
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, "http://jingyan.baidu.com/article/676629973a34f754d51b843d.html");
            params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "海工词典");//APP名称
            doShareToQQ(params);
        }

        if (!share.packageName.isEmpty()) {
        } else {
            // 分享到其他,调用安卓系统分享
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            File f = new File(mImgPath);
            if ((f != null) && (f.exists()) && (f.isFile())) {
                intent.setType("image/png");
                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
            }
            intent.putExtra(Intent.EXTRA_TEXT, msgText); // 附带的说明信息
            intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
            intent.setType("image/*"); // 分享图片
            startActivity(Intent.createChooser(intent, "分享"));
        }
    }

    // 执行分享
    private void doShareToQQ(final Bundle params) {
        // QQ分享要在主线程做
        ThreadManager.getMainHandler().post(new Runnable() {

            @Override
            public void run() {
                if (null != MainActivity.mTencent) {
                    MainActivity.mTencent.shareToQQ(shareActivity, params, qqShareListener);
                }
            }
        });
    }

    // 分享完成后的监听方法
    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {
        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub
        }
    };

    // 判断应用的包名是否存在
    public boolean isAvilible(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();

        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (((PackageInfo) pinfo.get(i)).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }

    //获得屏幕方向
    public int getScreenOrientation() {
        int landscape = 0;
        int portrait = 1;
        Point pt = new Point();
        getWindow().getWindowManager().getDefaultDisplay().getSize(pt);
        int width = pt.x;
        int height = pt.y;
        return width > height ? portrait : landscape;
    }

    //填充布局的适配器
    private final class MyAdapter extends BaseAdapter {
        private static final int image_id = 256;
        private static final int tv_id = 512;

        public MyAdapter() {
        }

        public int getCount() {
            return mListData.size();
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0L;
        }

        private View getItemView() {
            LinearLayout item = new LinearLayout(context);
            item.setOrientation(1);
            int padding = (int) (10.0F * mDensity);
            item.setPadding(padding, padding, padding, padding);
            item.setGravity(17);

            ImageView iv = new ImageView(context);
            item.addView(iv);
            iv.setLayoutParams(new LinearLayout.LayoutParams(-2, -2));
            iv.setId(image_id);

            TextView tv = new TextView(context);
            item.addView(tv);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(-2, -2);
            layoutParams.topMargin = ((int) (5.0F * mDensity));
            tv.setLayoutParams(layoutParams);
            tv.setTextColor(Color.parseColor("#212121"));
            tv.setTextSize(16.0F);
            tv.setId(tv_id);

            return item;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getItemView();
            }
            ImageView iv = (ImageView) convertView.findViewById(image_id);
            TextView tv = (TextView) convertView.findViewById(tv_id);
            ShareItem item = (ShareItem) mListData.get(position);
            iv.setImageResource(item.logo);
            tv.setText(item.title);
            return convertView;
        }
    }

    private class ShareItem {
        String title;
        int logo;
        String activityName;
        String packageName;

        public ShareItem(String title, int logo, String activityName, String packageName) {
            this.title = title;
            this.logo = logo;
            this.activityName = activityName;
            this.packageName = packageName;
        }
    }

    void init(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getResources().getDisplayMetrics();
        this.mDensity = dm.density;
        this.mListData = new ArrayList<ShareItem>();
        this.mListData.add(
                new ShareItem("微信", R.drawable.logo_wechat, "com.tencent.mm.ui.tools.ShareImgUI", "com.tencent.mm"));
        this.mListData.add(new ShareItem("朋友圈", R.drawable.logo_wechatmoments,
                "com.tencent.mm.ui.tools.ShareToTimeLineUI", "com.tencent.mm"));
        this.mListData.add(new ShareItem("QQ", R.drawable.logo_qq, "com.tencent.mobileqq.activity.JumpActivity",
                "com.tencent.mobileqq"));
        this.mListData.add(new ShareItem("空间", R.drawable.logo_qzone, "com.qzone.ui.operation.QZonePublishMoodActivity",
                "com.qzone"));
        this.mListData
                .add(new ShareItem("新浪", R.drawable.logo_sinaweibo, "com.sina.weibo.EditActivity", "com.sina.weibo"));
        this.mListData.add(new ShareItem("微博", R.drawable.logo_tencentweibo,
                "com.tencent.WBlog.intentproxy.TencentWeiboIntent", "com.tencent.WBlog"));
        this.mListData.add(new ShareItem("其他", R.drawable.logo_other, "", ""));

        this.mLayout = new LinearLayout(context);
        this.mLayout.setOrientation(1);
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2);
        params.leftMargin = ((int) (5.0F * this.mDensity));
        params.rightMargin = ((int) (5.0F * this.mDensity));
         // 设置占屏比
        params.height = (int) (d.getHeight() * 0.98); // 高度设置为屏幕的0.3
        params.width = (int) (d.getWidth() * 0.40); // 宽度设置为屏幕的0.5
        this.mLayout.setLayoutParams(params);
        this.mLayout.setBackgroundColor(Color.parseColor("#D9DEDF"));

        this.mGridView = new GridView(context);
        this.mGridView.setLayoutParams(new ViewGroup.LayoutParams(-1, -2));
        this.mGridView.setGravity(17);
        this.mGridView.setHorizontalSpacing((int) (5.0F * this.mDensity));
        this.mGridView.setVerticalSpacing(0);// 两行之间的间距
        this.mGridView.setStretchMode(1);
        this.mGridView.setColumnWidth((int) (88.0F * this.mDensity));
        this.mGridView.setHorizontalScrollBarEnabled(false);
        this.mGridView.setVerticalScrollBarEnabled(false);
        this.mLayout.addView(this.mGridView);
        Intent intent = getIntent();
        this.msgTitle = intent.getStringExtra("title");
        this.msgText = intent.getStringExtra("content");
        this.mImgPath = intent.getStringExtra("picture");
    }

}

3、到此我要说我是调用腾讯官方的SDK提供的API实现的,毕竟腾讯为我们提供了这么方便的接口,不用多可惜。简单方便,适合初学者学习,在使用腾讯的SDK之前要先去腾讯开发者平台注册并下载SDK并获得APP_ID和APP_KEY(在这里没用到),下载地址:( http://wiki.open.qq.com/wiki/SDK 下载)
如果没有注册过腾讯的APP_ID,那就注册一个,秒注册,很快。地址:( http://wiki.open.qq.com/wiki/ 注册成为开发者 ),注:地址要复制完全哦!
下载完成后将两个Jar包导入自己项目的libs下:


到这里你会发现你复制进去的代码错误少了很多,但是有一个mTencent还是没有,那是因为这个 mTencent是Tencent类的实例,需要写在主线程中,也就是你的MainActivity中,加上这一句:

//Tencent类是SDK的主要实现类,开发者可通过Tencent类访问腾讯开放的OpenAPI。
public static Tencent mTencent;
mTencent=Tencent.createInstance("你的APP_ID",getApplicationContext());

4、到这里代码中应该就没错误了吧(图标换成自己的),下边是AndroidMainifest.xml文件中要添加的部分, 这里边主要添加的是腾讯的辅助文件和你的Activity注册文件

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
<**权限我都复制过来了,如果你有重复的可以去掉**>
 <application
 <activity
            android:name="com.tencent.tauth.AuthActivity"
            android:launchMode="singleTask"
            android:noHistory="true" >
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="tencent你的APP_ID" />
            </intent-filter>
        </activity>
      <activity
            android:name="com.tencent.connect.common.AssistActivity"
            android:configChanges="orientation|keyboardHidden"
            android:screenOrientation="behind"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" >
        </activity>
     <activity
            android:name="com.dictionary.activity.ShareActivity"
            android:theme="@android:style/Theme.Dialog"
            android:windowSoftInputMode="stateVisible|adjustPan" >
        </activity>
</application>

好,到此结束,如果大家有什么问题的话可以跟我留言!谢谢大家的到来,祝大家工作愉快!









你可能感兴趣的:(android,qq,APP,手机,QQ空间)