Android(安卓)微信分享
16lz
2021-01-25
1..先去微信开放平台注册账号,然后创建应用,签名工具下载 , 创建成功得到appid和secret。
- 导入方式 Android接入指南
3. 注册到微信(可以在Application 、页面的 onCreate.... )
IWXAPI api = WXAPIFactory.createWXAPI(this, APP_ID, true); api.registerApp(APP_ID)
4.WXEntryActivity是微信回调的类
public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler { private Context context = WXEntryActivity.this; private void handleIntent(Intent paramIntent) { BaseApplication.api.handleIntent(paramIntent, this); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handleIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); handleIntent(intent); } // 微信发送请求到第三方应用时,会回调到该方法 @Override public void onReq(BaseReq req) { finish(); } // 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法 @Override public void onResp(BaseResp resp) { switch (resp.errCode) { case BaseResp.ErrCode.ERR_OK: if (ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX == resp.getType()) {//分享 Toast.makeText(context, "分享成功", Toast.LENGTH_LONG).show(); finish(); break; } break; case BaseResp.ErrCode.ERR_USER_CANCEL: Toast.makeText(this, " 取消 ", Toast.LENGTH_LONG).show(); finish(); break; case BaseResp.ErrCode.ERR_AUTH_DENIED: Toast.makeText(this, " 拒绝 ", Toast.LENGTH_LONG).show(); finish(); break; default: break; } }}
5.分享代码 以下5种类型
分享类型:(文本、图片、音乐、视频、网页)
1).文本分享代码:
WXTextObject textObj = new WXTextObject(); textObj.text = text; // 用WXTextObject对象初始化一个WXMediaMessage对象 WXMediaMessage msg = new WXMediaMessage(); msg.mediaObject = textObj; // 发送文本类型的消息时,title字段不起作用 msg.title = "Will be ignored"; msg.description = text; // 构造一个Req SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("text"); // transaction字段用于唯一标识一个请求 req.message = msg; req.scene = SendMessageToWX.Req.WXSceneSession; //设置发送给朋友 // req.scene = SendMessageToWX.Req.WXSceneTimeline; //设置发送到朋友圈 // 调用api接口发送数据到微信 api.sendReq(req);
2).图片分享代码:(包含 本地图片,SD卡图片,网络图片)
分享多张图片:https://www.jianshu.com/p/ce9f286bdd68
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.img); WXImageObject imgObj = new WXImageObject(bmp); WXMediaMessage msg = new WXMediaMessage(); msg.mediaObject = imgObj; Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true); bmp.recycle(); msg.thumbData = Util.bmpToByteArray(thumbBmp, true); // 设置所图; SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("img"); req.message = msg; req.scene = SendMessageToWX.Req.WXSceneSession; //设置发送给朋友 // req.scene = SendMessageToWX.Req.WXSceneTimeline; //设置发送到朋友圈 api.sendReq(req);
3).音乐分享代码
WXMusicObject music = new WXMusicObject(); music.musicUrl = "http://staff2.ustc.edu.cn/~wdw/softdown/index.asp/0042515_05.ANDY.mp3"; WXMediaMessage msg = new WXMediaMessage(); msg.mediaObject = music; msg.title = "标题"; msg.description = "描述信息"; Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.photo); msg.thumbData = Util.bmpToByteArray(thumb, true); SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("music"); req.message = msg; req.scene = SendMessageToWX.Req.WXSceneSession; //设置发送给朋友 // req.scene = SendMessageToWX.Req.WXSceneTimeline; //设置发送到朋友圈 api.sendReq(req);
4).视频分享代码
WXVideoObject video = new WXVideoObject(); video.videoUrl = "url....mp4";//mp4视频路径 WXMediaMessage msg = new WXMediaMessage(video); msg.title = "标题"; msg.description = "描述信息"; Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.photo); msg.thumbData = Util.bmpToByteArray(thumb, true); SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("video"); req.message = msg; req.scene = SendMessageToWX.Req.WXSceneSession; //设置发送给朋友 // req.scene = SendMessageToWX.Req.WXSceneTimeline; //设置发送到朋友圈 api.sendReq(req);
5).网页分享代码
WXWebpageObject webpage = new WXWebpageObject(); webpage.webpageUrl = "http://www.baidu.com"; WXMediaMessage msg = new WXMediaMessage(webpage); msg.title = "标题"; msg.description = "描述信息"; Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.photo); msg.thumbData = Util.bmpToByteArray(thumb, true); SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("webpage"); req.message = msg; req.scene = SendMessageToWX.Req.WXSceneSession; //设置发送给朋友 // req.scene = SendMessageToWX.Req.WXSceneTimeline; //设置发送到朋友圈 api.sendReq(req);
补充: buildTransaction方法 和 Util代码
- buildTransaction方法
private String buildTransaction(final String type) { return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis(); }
2.Util代码
public class Util { private static final String TAG = "SDK_Sample.Util"; public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) { ByteArrayOutputStream output = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, output); if (needRecycle) { bmp.recycle(); } byte[] result = output.toByteArray(); try { output.close(); } catch (Exception e) { e.printStackTrace(); } return result; } public static byte[] getHtmlByteArray(final String url) { URL htmlUrl = null; InputStream inStream = null; try { htmlUrl = new URL(url); URLConnection connection = htmlUrl.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection)connection; int responseCode = httpConnection.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK){ inStream = httpConnection.getInputStream(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } byte[] data = inputStreamToByte(inStream); return data; } public static byte[] inputStreamToByte(InputStream is) { try{ ByteArrayOutputStream bytestream = new ByteArrayOutputStream(); int ch; while ((ch = is.read()) != -1) { bytestream.write(ch); } byte imgdata[] = bytestream.toByteArray(); bytestream.close(); return imgdata; }catch(Exception e){ e.printStackTrace(); } return null; } public static byte[] readFromFile(String fileName, int offset, int len) { if (fileName == null) { return null; } File file = new File(fileName); if (!file.exists()) { Log.i(TAG, "readFromFile: file not found"); return null; } if (len == -1) { len = (int) file.length(); } Log.d(TAG, "readFromFile : offset = " + offset + " len = " + len + " offset + len = " + (offset + len)); if(offset <0){ Log.e(TAG, "readFromFile invalid offset:" + offset); return null; } if(len <=0 ){ Log.e(TAG, "readFromFile invalid len:" + len); return null; } if(offset + len > (int) file.length()){ Log.e(TAG, "readFromFile invalid file len:" + file.length()); return null; } byte[] b = null; try { RandomAccessFile in = new RandomAccessFile(fileName, "r"); b = new byte[len]; // 创建合适文件大小的数组 in.seek(offset); in.readFully(b); in.close(); } catch (Exception e) { Log.e(TAG, "readFromFile : errMsg = " + e.getMessage()); e.printStackTrace(); } return b; } private static final int MAX_DECODE_PICTURE_SIZE = 1920 * 1440; public static Bitmap extractThumbNail(final String path, final int height, final int width, final boolean crop) { Assert.assertTrue(path != null && !path.equals("") && height > 0 && width > 0); BitmapFactory.Options options = new BitmapFactory.Options(); try { options.inJustDecodeBounds = true; Bitmap tmp = BitmapFactory.decodeFile(path, options); if (tmp != null) { tmp.recycle(); tmp = null; } Log.d(TAG, "extractThumbNail: round=" + width + "x" + height + ", crop=" + crop); final double beY = options.outHeight * 1.0 / height; final double beX = options.outWidth * 1.0 / width; Log.d(TAG, "extractThumbNail: extract beX = " + beX + ", beY = " + beY); options.inSampleSize = (int) (crop ? (beY > beX ? beX : beY) : (beY < beX ? beX : beY)); if (options.inSampleSize <= 1) { options.inSampleSize = 1; } // NOTE: out of memory error while (options.outHeight * options.outWidth / options.inSampleSize > MAX_DECODE_PICTURE_SIZE) { options.inSampleSize++; } int newHeight = height; int newWidth = width; if (crop) { if (beY > beX) { newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth); } else { newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight); } } else { if (beY < beX) { newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth); } else { newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight); } } options.inJustDecodeBounds = false; Log.i(TAG, "bitmap required size=" + newWidth + "x" + newHeight + ", orig=" + options.outWidth + "x" + options.outHeight + ", sample=" + options.inSampleSize); Bitmap bm = BitmapFactory.decodeFile(path, options); if (bm == null) { Log.e(TAG, "bitmap decode failed"); return null; } Log.i(TAG, "bitmap decoded size=" + bm.getWidth() + "x" + bm.getHeight()); final Bitmap scale = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true); if (scale != null) { bm.recycle(); bm = scale; } if (crop) { final Bitmap cropped = Bitmap.createBitmap(bm, (bm.getWidth() - width) >> 1, (bm.getHeight() - height) >> 1, width, height); if (cropped == null) { return bm; } bm.recycle(); bm = cropped; Log.i(TAG, "bitmap croped size=" + bm.getWidth() + "x" + bm.getHeight()); } return bm; } catch (final OutOfMemoryError e) { Log.e(TAG, "decode bitmap failed: " + e.getMessage()); options = null; } return null; }}
bug记录
1.微信分享出错问题,MicroMsg.SDK.WXMediaMessage: checkArgs fail, thumbData is invalid MicroMsg.SDK.WXApiImplV10: sendReq checkArgs fail
解决方法 :分享图片大小不能大于32kb。把图片改小与32KB就行了。
更多相关文章
- 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
- android上代码去执行"su"命令
- listView常用属性设置
- android自动关机代码
- android 打开系统程序 显示系统图片与视频(用于备忘)
- android c和java代码中获取配置属性
- Android自定义控件之自定义进度条
- 如何单独编译Android源代码中的模块
- [android]android自动化测试十之单元测试实例