安卓实现微信分享——完整

来源:互联网 发布:手机看片下什么软件 编辑:程序博客网 时间:2024/04/29 22:13

一直比较忙,这个案例也是纠结了好救才写完,官方的开发文档还是比较清楚的。

由于过程比较复杂,我还是先说一下步骤,不然一切都是徒劳的。


1:新建DEMO工程,我是 项目名字=picShared    包名字=com.example.picshared

2:去微信官网下载jar包  和debug.keys   下载地址:https://open.weixin.qq.com/cgi-bin/showdocument?                     action=dir_list&t=resource/res_list&verify=1&id=1417751808&token=&lang=zh_CN

3:把liba这个jar包考入项目。   右键点击项目----builder path ---addJar   ,吧刚才的lim的jar包导入进去。  然后程序运行一边,建议用真机运行

签名工具地址:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419319167&lang=zh_CN

4:在微信平台顺便把签名工具生成下载下来,安装到手机,把自己的包名输入会生成签名,签名的数字和 MD5一样(谨记)如果没有步奏三,这一步没用,必须先执行3

4:带着签名数据,去微信官网创建项目,等待审核,

5:之后就是代码部分了,这个就不解释了额,注释很清楚了,直接上代码,

6:  WXEntryActivity 这个类不要改名字,一个字母都不要错,放在一个新的类中。里面的APPID=   要改成自己在围上上面申请的ID。


代码如下,

package com.example.picshared.wxapi;import com.example.picshared.R;import com.example.picshared.SystemUtil;import com.example.picshared.WXUtil;import com.tencent.mm.sdk.openapi.BaseReq;import com.tencent.mm.sdk.openapi.BaseResp;import com.tencent.mm.sdk.openapi.IWXAPI;import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;import com.tencent.mm.sdk.openapi.WXAPIFactory;import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.view.KeyEvent;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;import android.widget.Toast;public class WXEntryActivity extends Activity implements IWXAPIEventHandler {private final String WX_PACKAGE_NAME = "com.tencent.mm";public static final String APP_ID = "wx5d4ed9e837d2733f";private Button sendTextBtn, sendPicBtn, sendLocalBtn, sendUrlBtn, cameraBtn, musicBtn;private ImageView iv = null;private EditText et_text;// IWXAPI 是第三方app和微信通信的openapi接口private IWXAPI api;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// 通过WXAPIFactory工厂,获取IWXAPI的实例api = WXAPIFactory.createWXAPI(WXEntryActivity.this, APP_ID, true);api.handleIntent(getIntent(), WXEntryActivity.this);api.registerApp(APP_ID);// 初始化控件initView();setFunction();}private void initView() {et_text=(EditText) findViewById(R.id.text);sendTextBtn = (Button) findViewById(R.id.sendTextBtn);sendPicBtn = (Button) findViewById(R.id.sendPicBtn);sendLocalBtn = (Button) findViewById(R.id.sendLocalBtn);sendUrlBtn = (Button) findViewById(R.id.sendUrlBtn);cameraBtn = (Button) findViewById(R.id.cameraBtn);musicBtn = (Button) findViewById(R.id.musicBtn);// 检测是否安装微信软件boolean result = new SystemUtil(WXEntryActivity.this).isInstallWx(WX_PACKAGE_NAME);if (result) {Toast.makeText(WXEntryActivity.this, "已安装微信", Toast.LENGTH_SHORT).show(); } else {Toast.makeText(WXEntryActivity.this, "未安装微信", Toast.LENGTH_SHORT).show();}}private void setFunction() {sendTextBtn.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {String text = et_text.getText().toString();new WXUtil(WXEntryActivity.this, api).updateWXStatus(text, "测试");finish();}});sendPicBtn.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.draw_ad_top);new WXUtil(WXEntryActivity.this, api).uploadPic(bmp);finish();}});sendLocalBtn.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {new SystemUtil(WXEntryActivity.this).openLocalPic();}});sendUrlBtn.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {new Thread() {  public void run() {String url = "http://pic5.duowan.com/pc/1211/215711467256/215711598211.jpg";new WXUtil(WXEntryActivity.this, api).uploadUrlPic(url);finish();}}.start();}});cameraBtn.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {new SystemUtil(WXEntryActivity.this).openCamera();}});musicBtn.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {        new WXUtil(WXEntryActivity.this, api)    .uploadMusic("http://staff2.ustc.edu.cn/~wdw/softdown/index.asp/0042515_05.ANDY.mp3");finish();}});}  protected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (requestCode == 0) {if (resultCode == RESULT_OK) {new WXUtil(WXEntryActivity.this, api).uploadLocalPic(data);finish();}}if (requestCode == 1) {if (resultCode == RESULT_OK) {new WXUtil(WXEntryActivity.this, api).uploadCameraPic(data);finish();}}}protected void onNewIntent(Intent intent) {super.onNewIntent(intent);setIntent(intent);api.handleIntent(intent, this);}// 微信发送请求到第三方应用时,会回调到该方法public void onReq(BaseReq req) {}// 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法public void onResp(BaseResp resp) {String result = "";switch (resp.errCode) {case BaseResp.ErrCode.ERR_OK:result = "发送成功";break;case BaseResp.ErrCode.ERR_USER_CANCEL:result = "取消";break;case BaseResp.ErrCode.ERR_AUTH_DENIED:result = "发送失败";break;default:result = "出现异常";break;}Toast.makeText(this, result, 1).show();}}========================================================package com.example.picshared;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.sql.Date;import java.text.SimpleDateFormat;import android.annotation.SuppressLint;import android.graphics.Bitmap;import android.os.Environment;public class FileUtils {/*** 将Bitmap保存在本地* * @param mBitmap* @return*/@SuppressLint("SimpleDateFormat")public String saveBitmap(Bitmap mBitmap) {try {String sdCardPath = "";if (SystemUtil.hasSdCard()) {sdCardPath = Environment.getExternalStorageDirectory().getPath();} else {}String filePath = sdCardPath + "/" + "myImg/";Date date = new Date(System.currentTimeMillis());SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");// 时间格式-显示方式String imgPath = filePath + sdf.format(date) + ".png";File file = new File(filePath);if (!file.exists()) {file.mkdirs();}File imgFile = new File(imgPath);if (!imgFile.exists()) {imgFile.createNewFile();}FileOutputStream fOut = new FileOutputStream(imgFile);mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);fOut.flush();if (fOut != null) {fOut.close();}return imgPath;} catch (IOException e) {e.printStackTrace();}return null;}}=========================================================================package com.example.picshared;import android.app.Activity;import android.content.Intent;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.os.Environment;import android.provider.MediaStore;public class SystemUtil {private static Activity mActivity = null;public SystemUtil(Activity activity) {mActivity = activity;}/** 打开本地图片 */public void openLocalPic() {Intent i = new Intent(Intent.ACTION_GET_CONTENT);i.addCategory(Intent.CATEGORY_OPENABLE);i.setType("image/*");mActivity.startActivityForResult(i, 0);}/** 打开相机 */public void openCamera() {Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);mActivity.startActivityForResult(intent, 1);}/** 打开微信 */public void openWx(String packageName) {PackageManager manager = mActivity.getPackageManager();Intent intent = manager.getLaunchIntentForPackage(packageName);mActivity.startActivity(intent);}/** 是否安装微信 */public boolean isInstallWx(String packageName) {try {PackageManager manager = mActivity.getPackageManager();PackageInfo info = manager.getPackageInfo(packageName,PackageManager.GET_ACTIVITIES);if (info != null) {return true;}} catch (Exception e) {e.printStackTrace();}return false;}/*** 是否存在SDCard* */public static final boolean hasSdCard() {if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {return true;}return false;}}


=====================================================================================

package com.example.picshared;import java.io.ByteArrayOutputStream;import java.net.URL;import android.app.Activity;import android.content.Intent;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.Bitmap.CompressFormat;import android.graphics.BitmapFactory;import android.net.Uri;import com.tencent.mm.sdk.openapi.IWXAPI;import com.tencent.mm.sdk.openapi.SendMessageToWX;import com.tencent.mm.sdk.openapi.WXImageObject;import com.tencent.mm.sdk.openapi.WXMediaMessage;import com.tencent.mm.sdk.openapi.WXMusicObject;import com.tencent.mm.sdk.openapi.WXTextObject;public class WXUtil {private IWXAPI api;private Activity mActivity = null;private final int THUMB_SIZE = 150;private String filePath = null;private Bitmap mBitmap = null;public WXUtil(Activity activity, IWXAPI api) {mActivity = activity;this.api = api;}/*** 更新为微信朋友圈状态* * @param text*            文本* @param desc*            描述*/public void updateWXStatus(String text, String desc) {WXTextObject textObj = new WXTextObject();textObj.text = text;// 用WXTextObject对象初始化一个WXMediaMessage对象WXMediaMessage msg = new WXMediaMessage();msg.mediaObject = textObj;// 发送文本类型的消息时,title字段不起作用// msg.title = "Will be ignored";msg.description = desc;// 构造一个ReqSendMessageToWX.Req req = new SendMessageToWX.Req();req.transaction = buildTransaction("text"); //// transaction字段用于唯一标识一个请求req.message = msg;req.scene = SendMessageToWX.Req.WXSceneTimeline;// 调用api接口发送数据到微信api.sendReq(req);}/*** 上传本地照片* * @param data*            onActivityResult 中Intent返回数据*/public void uploadLocalPic(Intent data) {Uri uri = data.getData();// 相册图片路径Cursor cursor = mActivity.getContentResolver().query(uri, null, null,null, null);cursor.moveToFirst();String imgPath = cursor.getString(1); // 图片文件路径WXImageObject imgObj = new WXImageObject();imgObj.setImagePath(imgPath);WXMediaMessage msg = new WXMediaMessage();msg.mediaObject = imgObj;Bitmap bmp = BitmapFactory.decodeFile(imgPath);Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE,THUMB_SIZE, true);bmp.recycle();msg.thumbData = bmpToByteArray(thumbBmp, true);SendMessageToWX.Req req = new SendMessageToWX.Req();req.transaction = buildTransaction("img");req.message = msg;req.scene = SendMessageToWX.Req.WXSceneTimeline;api.sendReq(req);}/*** 上传Bitmap至微信朋友圈* * @param bitmap*/public void uploadPic(Bitmap bitmap) {WXImageObject imgObj = new WXImageObject(bitmap);WXMediaMessage msg = new WXMediaMessage();msg.mediaObject = imgObj;Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE,THUMB_SIZE, true);bitmap.recycle();msg.thumbData = bmpToByteArray(thumbBmp, true); // 设置缩略图SendMessageToWX.Req req = new SendMessageToWX.Req();req.transaction = buildTransaction("img");req.message = msg;req.scene = SendMessageToWX.Req.WXSceneTimeline;api.sendReq(req);}/*** 照相上传* * @param data*            onActivityResult 中Intent返回数据*/public void uploadCameraPic(Intent data) {if (data != null) {// HTCif (data.getData() != null) {// 根据返回的URI获取对应的SQLite信息Cursor cursor = mActivity.getContentResolver().query(data.getData(), null, null, null, null);if (cursor.moveToFirst()) {filePath = cursor.getString(cursor.getColumnIndex("_data"));// 获取绝对路径}cursor.close();} else {// 三星 小米(小米手机不会自动存储DCIMmBitmap = (Bitmap) (data.getExtras() == null ? null : data.getExtras().get("data"));}// 直接强转报错 这个主要是为了去高宽比例Bitmap bitmap = mBitmap == null ? null : (Bitmap) mBitmap;if (bitmap == null) {/*** 该Bitmap是为了获取压缩后的文件比例 如果没有缩略图的比例* 就获取真实文件的比例(真实图片比例会耗时很长,所以如果有缩略图最好)*/bitmap = BitmapFactory.decodeFile(filePath);}String imgPath = new FileUtils().saveBitmap(bitmap);if (imgPath != null && !"".equals(imgPath)) {WXImageObject imgObj = new WXImageObject();imgObj.setImagePath(imgPath);WXMediaMessage msg = new WXMediaMessage();msg.mediaObject = imgObj;Bitmap bmp = BitmapFactory.decodeFile(imgPath);Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE,THUMB_SIZE, true);bmp.recycle();msg.thumbData = bmpToByteArray(thumbBmp, true);SendMessageToWX.Req req = new SendMessageToWX.Req();req.transaction = buildTransaction("img");req.message = msg;req.scene = SendMessageToWX.Req.WXSceneTimeline;api.sendReq(req);}}}/*** 上传Url类型照片* * @param url*            图片链接地址*/public void uploadUrlPic(String url) {try {WXImageObject imgObj = new WXImageObject();imgObj.imageUrl = url;WXMediaMessage msg = new WXMediaMessage();msg.mediaObject = imgObj;Bitmap bmp = BitmapFactory.decodeStream(new URL(url).openStream());Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE,THUMB_SIZE, true);bmp.recycle();msg.thumbData = bmpToByteArray(thumbBmp, true);SendMessageToWX.Req req = new SendMessageToWX.Req();req.transaction = buildTransaction("img");req.message = msg;req.scene = SendMessageToWX.Req.WXSceneTimeline;api.sendReq(req);} catch (Exception e) {e.printStackTrace();}}public void uploadMusic(String url) {WXMusicObject music = new WXMusicObject();// music.musicUrl = "http://www.baidu.com";music.musicUrl = url;// music.musicUrl="http://120.196.211.49/XlFNM14sois/AKVPrOJ9CBnIN556OrWEuGhZvlDF02p5zIXwrZqLUTti4o6MOJ4g7C6FPXmtlh6vPtgbKQ==/31353278.mp3";WXMediaMessage msg = new WXMediaMessage();msg.mediaObject = music;msg.title = "Music Title Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long";msg.description = "Music Album Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long Very Long";Bitmap thumb = BitmapFactory.decodeResource(mActivity.getResources(),R.drawable.draw_ad_top);msg.thumbData = bmpToByteArray(thumb, true);SendMessageToWX.Req req = new SendMessageToWX.Req();req.transaction = buildTransaction("music");req.message = msg;req.scene = SendMessageToWX.Req.WXSceneTimeline;api.sendReq(req);}private String buildTransaction(final String type) {return (type == null) ? String.valueOf(System.currentTimeMillis()): type + System.currentTimeMillis();}private byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {ByteArrayOutputStream output = new ByteArrayOutputStream();bmp.compress(CompressFormat.JPEG, 100, output);if (needRecycle) {bmp.recycle();}byte[] result = output.toByteArray();try {output.close();} catch (Exception e) {e.printStackTrace();}return result;}}


================================================================

界面代码<?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" >    <EditText        android:id="@+id/text"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:hint="文本发送" />    <Button        android:id="@+id/sendTextBtn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:text="文本发送" />    <TextView        android:layout_width="match_parent"        android:layout_height="1dp"        android:background="@android:color/black" />    <Button        android:id="@+id/sendPicBtn"       android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:text="上传固定图片" />    <Button        android:id="@+id/sendLocalBtn"       android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:text="上传本地图片" />    <Button        android:id="@+id/sendUrlBtn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:text="上传url图片" />    <Button        android:id="@+id/cameraBtn"       android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:text="照片上传" />    <Button        android:id="@+id/musicBtn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:text="上传音乐" /></LinearLayout>




=========================================================================还有就是权限了,

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.picshared"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="14"        android:targetSdkVersion="19" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.picshared.wxapi.WXEntryActivity"             android:exported="true"            android:label="@string/app_name"             android:launchMode="singleTop">             <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>            <intent-filter>                <action android:name="android.intent.action.VIEW" />                <category android:name="android.intent.category.DEFAULT" />                <data android:scheme="sdksample" />            </intent-filter>        </activity>    </application>         <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />    <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.READ_PHONE_STATE" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /></manifest>



有问题的直接看代码附件,网上好多写的都永不了,亲测能用。请吐槽




0 0
原创粉丝点击