Commit f23b81d358a8b02f46af1712b18f5120dc874089

Authored by wdn127929
1 parent 1a0657cf

安卓企业微信集成OK

... ... @@ -4684,7 +4684,7 @@ class InvicationPageState extends State<InvicationPage>
HEmptyView(20),
RoundButton(
text: '企业微信通知',
width: ScreenUtil().setWidth(100 * 2),
width: ScreenUtil().setWidth(110 * 2),
height: ScreenUtil().setWidth(96),
fontSize: 30,
textColor: MyColours.color_999999,
... ... @@ -4721,105 +4721,62 @@ class InvicationPageState extends State<InvicationPage>
],
),
RoundButton(
text: '微信通知',
height: ScreenUtil().setWidth(48 * 2),
fontSize: 38,
gradientStart: Colors.transparent,
gradientEnd: Colors.transparent,
radius: ScreenUtil().setWidth(16),
isBold: true,
onPressed: () async {
if (_nameNode.hasFocus ||
_phoneNode.hasFocus ||
_cusdemNode.hasFocus) {
needWechat = true;
_showConfirmWidget(
needWechat: true,
callback: () async {
if (ObjectUtil.isEmpty(
_baseIndoProvider.baseInfoSunModel) ||
ObjectUtil.isEmpty(_baseIndoProvider
.baseInfoSunModel.phone)) {
// Utils.showToast('请填写经理的联系电话');
DialogUtil.cupertinoAlertDialog(context,
title: "填写个人信息",
content:
"暂未填写您的联系信息,请先前往填写,个人信息将会展示给您的顾客。",
lTitle: "取消",
rTitle: "去填写",
lCallback: () {}, rCallback: () {
_goBaseInfoPage();
});
text: '微信通知',
height: ScreenUtil().setWidth(48 * 2),
fontSize: 38,
gradientStart: Colors.transparent,
gradientEnd: Colors.transparent,
radius: ScreenUtil().setWidth(16),
isBold: true,
onPressed: () async {
if (_nameNode.hasFocus ||
_phoneNode.hasFocus ||
_cusdemNode.hasFocus) {
needWechat = true;
_showConfirmWidget(
needWechat: true,
callback: () async {
if (ObjectUtil.isEmpty(
_baseIndoProvider.baseInfoSunModel) ||
ObjectUtil.isEmpty(
_baseIndoProvider.baseInfoSunModel.phone)) {
// Utils.showToast('请填写经理的联系电话');
DialogUtil.cupertinoAlertDialog(context,
title: "填写个人信息",
content: "暂未填写您的联系信息,请先前往填写,个人信息将会展示给您的顾客。",
lTitle: "取消",
rTitle: "去填写",
lCallback: () {}, rCallback: () {
_goBaseInfoPage();
});
return;
}
if (youhui != '选择优惠') {
Map<String, String> params = {
"rid": widget.rid,
"aid":
'${couponProvider.couponListSelect[couponSelectIndex].id}'
};
bool isSuc = await couponProvider
.setActivityAsReserve(context, params);
if (isSuc) {
couponProvider.hasModify = true;
bus.emit("refresh_book_list");
bool isSuccess =
await Utils.goShareInvicationToWeChat(
context,
widget.rid,
Provider.of<UserModel>(context,
listen: false)
.user
.openid,
);
print(isSuccess);
if (isSuccess) {
_addForward();
}
}
} else {
bool isSuccess =
await Utils.goShareInvicationToWeChat(
context,
widget.rid,
Provider.of<UserModel>(context,
listen: false)
.user
.openid);
if (isSuccess) {
_addForward();
}
return;
}
if (youhui != '选择优惠') {
Map<String, String> params = {
"rid": widget.rid,
"aid":
'${couponProvider.couponListSelect[couponSelectIndex].id}'
};
bool isSuc = await couponProvider
.setActivityAsReserve(context, params);
if (isSuc) {
couponProvider.hasModify = true;
bus.emit("refresh_book_list");
bool isSuccess =
await Utils.goShareInvicationToWeChat(
context,
widget.rid,
Provider.of<UserModel>(context, listen: false)
.user
.openid,
);
print(isSuccess);
if (isSuccess) {
_addForward();
}
});
removeOverlay();
} else {
if (ObjectUtil.isEmpty(
_baseIndoProvider.baseInfoSunModel) ||
ObjectUtil.isEmpty(
_baseIndoProvider.baseInfoSunModel.phone)) {
// Utils.showToast('请填写经理的联系电话');
DialogUtil.cupertinoAlertDialog(context,
title: "填写个人信息",
content: "暂未填写您的联系信息,请先前往填写,个人信息将会展示给您的顾客。",
lTitle: "取消",
rTitle: "去填写",
lCallback: () {}, rCallback: () {
_goBaseInfoPage();
});
return;
}
if (youhui != '选择优惠') {
Map<String, String> params = {
"rid": widget.rid,
"aid":
'${couponProvider.couponListSelect[couponSelectIndex].id}'
};
bool isSuc = await couponProvider
.setActivityAsReserve(context, params);
if (isSuc) {
couponProvider.hasModify = true;
bus.emit("refresh_book_list");
}
} else {
bool isSuccess =
await Utils.goShareInvicationToWeChat(
context,
... ... @@ -4828,26 +4785,64 @@ class InvicationPageState extends State<InvicationPage>
listen: false)
.user
.openid);
print(isSuccess);
if (isSuccess) {
_addForward();
}
}
} else {
bool isSuccess =
await Utils.goShareInvicationToWeChat(
context,
widget.rid,
Provider.of<UserModel>(context,
listen: false)
.user
.openid);
if (isSuccess) {
_addForward();
}
});
removeOverlay();
} else {
if (ObjectUtil.isEmpty(
_baseIndoProvider.baseInfoSunModel) ||
ObjectUtil.isEmpty(
_baseIndoProvider.baseInfoSunModel.phone)) {
// Utils.showToast('请填写经理的联系电话');
DialogUtil.cupertinoAlertDialog(context,
title: "填写个人信息",
content: "暂未填写您的联系信息,请先前往填写,个人信息将会展示给您的顾客。",
lTitle: "取消",
rTitle: "去填写",
lCallback: () {}, rCallback: () {
_goBaseInfoPage();
});
return;
}
if (youhui != '选择优惠') {
Map<String, String> params = {
"rid": widget.rid,
"aid":
'${couponProvider.couponListSelect[couponSelectIndex].id}'
};
bool isSuc = await couponProvider.setActivityAsReserve(
context, params);
if (isSuc) {
couponProvider.hasModify = true;
bus.emit("refresh_book_list");
bool isSuccess =
await Utils.goShareInvicationToWeChat(
context,
widget.rid,
Provider.of<UserModel>(context, listen: false)
.user
.openid);
print(isSuccess);
if (isSuccess) {
_addForward();
}
}
})
} else {
bool isSuccess = await Utils.goShareInvicationToWeChat(
context,
widget.rid,
Provider.of<UserModel>(context, listen: false)
.user
.openid);
if (isSuccess) {
_addForward();
}
}
}
})
])),
],
));
... ...
... ... @@ -428,14 +428,14 @@ class _FeastDishSharePageState extends State<FeastDishSharePage> {
fontSize: 36,
isBold: false,
onPressed: () {
// ShareHelper.onShareWx(
// context,
// boundaryKey: boundaryKey,
// );
ShareHelper.onShareWxwork(
ShareHelper.onShareWx(
context,
boundaryKey: boundaryKey,
);
// ShareHelper.onShareWxwork(
// context,
// boundaryKey: boundaryKey,
// );
// NavigatorUtil.goFeastDishSharePage(context);
},
... ...
... ... @@ -2308,7 +2308,7 @@ class TableManagerPageState extends State<TableManagerPage> {
children: [
RoundButton(
text: '仅占座',
width: ScreenUtil().setWidth(64 * 2),
width: ScreenUtil().setWidth(100 * 2),
height: ScreenUtil().setWidth(96),
fontSize: 24,
textColor: MyColours.color_515151,
... ... @@ -2320,43 +2320,43 @@ class TableManagerPageState extends State<TableManagerPage> {
// _onlyReserve();
JhCommonUtils.debounce(() => _onlyReserve(), 500);
}),
HEmptyView(22),
RoundButton(
text: '短信通知',
width: ScreenUtil().setWidth(64 * 2),
height: ScreenUtil().setWidth(96),
fontSize: 24,
textColor: MyColours.color_515151,
gradientStart: MyColours.color_f3f3f3,
gradientEnd: MyColours.color_f3f3f3,
radius: ScreenUtil().setWidth(8),
isBold: false,
onPressed: () {
setState(() {
wechatNotification = false;
});
},
),
HEmptyView(20),
RoundButton(
text: '企业微信通知',
width: ScreenUtil().setWidth(80 * 2),
height: ScreenUtil().setWidth(96),
fontSize: 24,
textColor: MyColours.color_515151,
gradientStart: MyColours.color_f3f3f3,
gradientEnd: MyColours.color_f3f3f3,
radius: ScreenUtil().setWidth(8),
isBold: false,
onPressed: () async {
JhCommonUtils.debounce(
() => _wechatReserve(false), 500);
},
),
HEmptyView(20),
// HEmptyView(22),
// RoundButton(
// text: '短信通知',
// width: ScreenUtil().setWidth(64 * 2),
// height: ScreenUtil().setWidth(96),
// fontSize: 24,
// textColor: MyColours.color_515151,
// gradientStart: MyColours.color_f3f3f3,
// gradientEnd: MyColours.color_f3f3f3,
// radius: ScreenUtil().setWidth(8),
// isBold: false,
// onPressed: () {
// setState(() {
// wechatNotification = false;
// });
// },
// ),
// HEmptyView(20),
// RoundButton(
// text: '企业微信通知',
// width: ScreenUtil().setWidth(80 * 2),
// height: ScreenUtil().setWidth(96),
// fontSize: 24,
// textColor: MyColours.color_515151,
// gradientStart: MyColours.color_f3f3f3,
// gradientEnd: MyColours.color_f3f3f3,
// radius: ScreenUtil().setWidth(8),
// isBold: false,
// onPressed: () async {
// JhCommonUtils.debounce(
// () => _wechatReserve(false), 500);
// },
// ),
HEmptyView(32),
Expanded(
child: RoundButton(
text: '微信通知',
text: '录入预订',
height: ScreenUtil().setWidth(96),
fontSize: 32,
gradientStart: MyColours.color_438E93,
... ... @@ -2423,7 +2423,7 @@ class TableManagerPageState extends State<TableManagerPage> {
// }
// } else {
// if (isWechat) {
NavigatorUtil.goInvicationPage(context, _model.row.id);
NavigatorUtil.goInvicationPage(context, _model.row.id);
// } else {
// bool isSuccess = await Utils.goShareInvicationToWeChat(
// context,
... ...
... ... @@ -2098,11 +2098,15 @@ class Utils {
bool registerResult = await flutterWxwork.registerApp(
'wwauthbdca186ec4257973000003', 'wwbdca186ec4257973', '1000003');
print(registerResult);
// isSuccess = await flutterWxwork.shareText(text: "dddddddd");
isSuccess = await flutterWxwork.shareMiniProgram(
userName: 'gh_487873d353b3@app',
path: _path,
hdImageData: _thumbnail,
title: _title);
userName: 'gh_487873d353b3@app',
path: _path,
hdImageData: _thumbnail,
title: _title,
description: _description,
);
// var isSuccess = await flutterWxwork.shareImage();
print(isSuccess);
... ...
package com.wxwork.flutter_wxwork;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private OnBitmapDownloadListener listener;
public DownloadImageTask(OnBitmapDownloadListener listener) {
this.listener = listener;
}
@Override
protected Bitmap doInBackground(String... urls) {
String urlString = urls[0];
Bitmap bitmap = null;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
listener.onBitmapDownloaded(bitmap);
}
public interface OnBitmapDownloadListener {
void onBitmapDownloaded(Bitmap bitmap);
}
}
\ No newline at end of file
... ...
... ... @@ -22,6 +22,36 @@ import com.tencent.wework.api.IWWAPIEventHandler;
import com.tencent.wework.api.WWAPIFactory;
import com.tencent.wework.api.model.BaseMessage;
import com.tencent.wework.api.model.WWAuthMessage;
import com.tencent.wework.api.model.WWMediaMiniProgram;
import com.tencent.wework.api.model.WWSimpleRespMessage;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import com.wxwork.flutter_wxwork.LoadImageUtil;
import com.wxwork.flutter_wxwork.NetWorkUtils;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
... ... @@ -49,6 +79,10 @@ public class FlutterWxworkPlugin implements FlutterPlugin, MethodCallHandler {
private Context context;
private static final int SHARE_MINI_PROGRAM_THUMB_LENGTH = 120 ;
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_wxwork");
... ... @@ -65,7 +99,7 @@ public class FlutterWxworkPlugin implements FlutterPlugin, MethodCallHandler {
if (call.method.equals("isAppInstalled")) {
boolean installed = iwwapi.isWWAppInstalled();
// if (installed) {
result.success(installed);
result.success(installed);
// } else {
// result.success("0");
// }
... ... @@ -75,7 +109,7 @@ public class FlutterWxworkPlugin implements FlutterPlugin, MethodCallHandler {
AGENTID = arguments.get("agentId");
boolean hasRegister = iwwapi.registerApp(SCHEMA);
// if (hasRegister) {
result.success(hasRegister);
result.success(hasRegister);
// } else {
// result.success("0");
// }
... ... @@ -105,9 +139,395 @@ public class FlutterWxworkPlugin implements FlutterPlugin, MethodCallHandler {
}
});
}else if (call.method.equals("shareImageNetWork")) {
// APPID = arguments.get("corpId");
// SCHEMA = arguments.get("scheme");
// AGENTID = arguments.get("agentId");
// boolean hasRegister = iwwapi.registerApp(SCHEMA);
// // if (hasRegister) {
// result.success(hasRegister);
// // } else {
// // result.success("0");
// // }
} else if (call.method.equals("shareImagePath")) {
}else if (call.method.equals("shareMiniProgram")) {
WWMediaMiniProgram miniProgram = new WWMediaMiniProgram();
miniProgram.appPkg = "com.naji.one_key";
miniProgram.appName = "周到安排商家";//app name of this android pkg
miniProgram.appId = APPID; //企业唯一标识。创建企业后显示在,我的企业 CorpID字段
miniProgram.agentId = AGENTID; //应用唯一标识。显示在具体应用下的 AgentId字段
miniProgram.schema = SCHEMA;
miniProgram.username = arguments.get("userName"); //必须是应用关联的小程序,注意要有@app后缀
miniProgram.description = arguments.get("description");
miniProgram.path = arguments.get("path");
//得到图片
DownloadImageTask task = new DownloadImageTask(new DownloadImageTask.OnBitmapDownloadListener() {
@Override
public void onBitmapDownloaded(Bitmap bitmap) {
//缩略图建议不超过32kb
Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 500, 400, true);
bitmap.recycle();
miniProgram.hdImageData = bmpToByteArray(thumbBmp, true);
// 在这里处理下载到的Bitmap对象
// miniProgram.hdImageData = getBytesFromBitmap(bitmap);
miniProgram.title = arguments.get("title");
iwwapi.sendMessage(miniProgram, new IWWAPIEventHandler() {
@Override
public void handleResp(BaseMessage resp) {
if(resp instanceof WWSimpleRespMessage){
WWSimpleRespMessage rsp = (WWSimpleRespMessage)resp;
// String t = "";
// Toast.makeText(MainActivity.this,
// t = "发小程序," + rsp.errCode + "," + rsp.errMsg,
// Toast.LENGTH_LONG).show();
Map<String, String> map = new HashMap<>();
map.put("code", String.valueOf(rsp.errCode));
map.put("errCode", String.valueOf(rsp.errMsg));
result.success(map);
}
}
});
}
});
Log.i("ExampleClass", "Value: " + arguments.get("hdImageData"));
task.execute(arguments.get("hdImageData"));
// LoadImageUtil loadImageUtil = new LoadImageUtil(context);
// Bitmap bitmap = loadImageUtil.loadBitmapByImgUrl(arguments.get("hdImageData"), new LoadImageUtil.CallBack() {
// @Override
// public void callBack(String imgUrl, Bitmap bitmap) {
// if(bitmap != null){
//// ImageView img = (ImageView) parent.findViewWithTag(imgUrl);
//// img.setImageBitmap(bitmap);
// miniProgram.hdImageData = getBytesFromBitmap(bitmap);
// miniProgram.title = arguments.get("title");
// iwwapi.sendMessage(miniProgram, new IWWAPIEventHandler() {
// @Override
// public void handleResp(BaseMessage resp) {
// if(resp instanceof WWSimpleRespMessage){
// WWSimpleRespMessage rsp = (WWSimpleRespMessage)resp;
//// String t = "";
//// Toast.makeText(MainActivity.this,
//// t = "发小程序," + rsp.errCode + "," + rsp.errMsg,
//// Toast.LENGTH_LONG).show();
//
// Map<String, String> map = new HashMap<>();
// map.put("code", String.valueOf(rsp.errCode));
// map.put("errCode", String.valueOf(rsp.errMsg));
//
//
// result.success(map);
// }
// }
// });
// }
//
// }
// });
// if(bitmap != null){//如果图片在缓存中,直接获取展示
// miniProgram.hdImageData = getBytesFromBitmap(bitmap);
// miniProgram.title = arguments.get("title");
// iwwapi.sendMessage(miniProgram, new IWWAPIEventHandler() {
// @Override
// public void handleResp(BaseMessage resp) {
// if(resp instanceof WWSimpleRespMessage){
// WWSimpleRespMessage rsp = (WWSimpleRespMessage)resp;
//// String t = "";
//// Toast.makeText(MainActivity.this,
//// t = "发小程序," + rsp.errCode + "," + rsp.errMsg,
//// Toast.LENGTH_LONG).show();
//
// Map<String, String> map = new HashMap<>();
// map.put("code", String.valueOf(rsp.errCode));
// map.put("errCode", String.valueOf(rsp.errMsg));
//
//
// result.success(map);
// }
// }
// });
// }
// Bitmap bitmap = getBitmapFromURL(arguments.get("hdImageData"));
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// bitmap.compress(Bitmap.CompressFormat.JPEG, 0, stream);
// byte[] byteArray = stream.toByteArray();
//
}else if (call.method.equals("shareText")) {
WWMediaText txt = new WWMediaText( arguments.get("text")
);
txt.appPkg = "com.naji.one_key";
txt.appName = "周到安排商家" ;
txt.appId = APPID; //企业唯一标识。创建企业后显示在,我的企业 CorpID字段
txt.agentId = AGENTID; //应用唯一标识。显示在具体应用下的 AgentId字段
iwwapi.sendMessage(txt);
}
else {
// result(FlutterMethodNotImplemented);
}
}
// 转换图片格式为字节数组
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 Bitmap compressBitmap(String imgPath, int targetWidth, int targetHeight, int quality, Bitmap.CompressFormat compressFormat) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imgPath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
float ratio = actualWidth / (float) actualHeight;
options.inSampleSize = 1;
while ((actualWidth / 2) > targetWidth && (actualHeight / 2) > targetHeight) {
actualWidth /= 2;
actualHeight /= 2;
options.inSampleSize *= 2;
}
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, targetWidth, (int) (targetWidth / ratio), true);
bitmap.recycle();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
scaledBitmap.compress(compressFormat, quality, byteArrayOutputStream);
scaledBitmap.recycle();
return BitmapFactory.decodeByteArray(byteArrayOutputStream.toByteArray(), 0, byteArrayOutputStream.size());
}
public static byte[] getBytesFromBitmap(Bitmap bitmap) {
// Bitmap compressedImage = compressBitmap(bitmap,100);
ByteBuffer byteBuffer = ByteBuffer.allocate(bitmap.getByteCount());
bitmap.copyPixelsToBuffer(byteBuffer);
return byteBuffer.array();
}
/**
* 压缩图片
*
* @param bitmap
* 被压缩的图片
* @param sizeLimit
* 大小限制
* @return
* 压缩后的图片
*/
private static Bitmap compressBitmap(Bitmap bitmap, long sizeLimit) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int quality = 10;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
// 循环判断压缩后图片是否超过限制大小
while(baos.toByteArray().length / 1024 > sizeLimit) {
// 清空baos
baos.reset();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
quality -= 10;
}
Bitmap newBitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, null);
return newBitmap;
}
// public static Bitmap compressBitmapToSize(Bitmap bitmap, int maxSizeKB) {
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// bitmap.compress(getBitmapCompressFormat(bitmap), 100, baos); // 假设压缩格式为JPEG
// int options = 100;
//
// int bytes = baos.toByteArray().length/1024;
////
// // 如果Bitmap的大小已经小于或等于指定的大小,则不需要进一步压缩
// while (bytes > maxSizeKB ) {
// // 每次减少质量,然后重新压缩
// options -= 5; // 降低质量
// baos.reset(); // 重置baos来清除数据
// bitmap.compress(getBitmapCompressFormat(bitmap), options, baos);
//
//
// bytes = baos.toByteArray().length/1024;
// }
//
//
//
//// while (baos.toByteArray().length / 1024 > maxSizeKB && options != 10) {
//// baos.reset(); // 清空baos以复用
//// options -= 10; // 每次减少10
//// bitmap.compress(getBitmapCompressFormat(bitmap), options, baos);
//// }
// ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
// Bitmap compressedBitmap = BitmapFactory.decodeStream(isBm, null, null);
// // 释放资源
// baos.reset();
// try {
// baos.close();
// isBm.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// return compressedBitmap;
// }
// public static Bitmap compressImage(Bitmap bitmap){
// int height = (int) ( bitmap.getHeight() * (512.0 / bitmap.getWidth()) );
// bitmap = Bitmap.createScaledBitmap(bitmap, 512, height, true);
// return bitmap;
// }
// public static Bitmap compressBitmapToSize(Bitmap image, int maxSizeKB) {
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// // 计算压缩比例
// int quality = 100;
// image.compress(Bitmap.CompressFormat.JPEG, quality, stream);
// // 如果图片大小大于指定大小,则以压缩质量为基准重复压缩
// while ((stream.toByteArray().length / 1024) > maxSizeKB && quality > 0) {
// stream.reset(); // 重置流以复用
// quality -= 5; // 每次减少5%的质量
// image.compress(getBitmapCompressFormat(image), quality, stream);
// }
// // 将流转换为字节
// byte[] imageBytes = stream.toByteArray();
// // 将字节转换为Bitmap
// Bitmap compressedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
// // 释放资源
//
//// 关闭流
// try {
// stream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// return compressedImage;
// }
// public static Bitmap compressBitmapToSize(Bitmap bitmap, int maxSizeKB) {
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// int quality = 100;
// int bytes = baos.toByteArray().length;
//
// // 如果Bitmap的大小已经小于或等于指定的大小,则不需要进一步压缩
// while (bytes > maxSizeKB ) {
// // 每次减少质量,然后重新压缩
// quality -= 5; // 降低质量
// baos.reset(); // 重置baos来清除数据
// bitmap.compress(getBitmapCompressFormat(bitmap), quality, baos);
//
//
// bytes = baos.toByteArray().length;
// }
//
// // 将压缩后的数据转换回Bitmap对象
// ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
// Bitmap compressedBitmap = BitmapFactory.decodeStream(isBm, null, null);
// // 关闭流
// try {
// baos.close();
// isBm.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// return compressedBitmap;
// }
public static Bitmap.CompressFormat getBitmapCompressFormat(Bitmap bitmap) {
Bitmap.Config config = bitmap.getConfig();
if (config == null) {
return Bitmap.CompressFormat.PNG;
}
switch (config) {
case RGB_565:
return Bitmap.CompressFormat.JPEG;
case ALPHA_8:
case ARGB_4444:
case ARGB_8888:
return Bitmap.CompressFormat.PNG;
default:
return Bitmap.CompressFormat.WEBP;
}
}
// public static Bitmap getBitmapFromURL(String imageUrl) {
// HttpURLConnection connection = null;
// try {
// URL url = new URL(imageUrl);
// connection = (HttpURLConnection) url.openConnection();
// connection.setDoInput(true);
// connection.connect();
// BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
// Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
// inputStream.close();
// return myBitmap;
// } catch (IOException e) {
// e.printStackTrace();
// return null;
// } finally {
// if (connection != null) {
// connection.disconnect();
// }
// }
// }
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
... ...
package com.wxwork.flutter_wxwork;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import java.lang.ref.SoftReference;
import java.util.HashMap;
/**
* Created by Administrator on 2017/9/5.
*/
public class LoadImageUtil {
private Context context;
private HashMap<String,SoftReference<Bitmap>> bitMaps;
public LoadImageUtil(Context context) {
this.context = context;
this.bitMaps = new HashMap<String,SoftReference<Bitmap>>();//实例化缓存容器
}
//回调的接口
public interface CallBack{
public void callBack(String imgUrl,Bitmap bitmap);
}
//加载图片,进行缓存
public Bitmap loadBitmapByImgUrl(final String imgUrl, final CallBack callBack){
// //先判断缓存中有没有图片,得到图片
// SoftReference<Bitmap> soft = bitMaps.get(imgUrl);
// if(soft != null){
// Bitmap bitmap = soft.get();//从软引用中获得bitmap
// if(bitmap != null){//缓存中有次图片,直接用
// return bitmap;
// }else{
// bitMaps.remove(imgUrl);//key(图片的url)对应的bitmap消耗了,key也没有意义
// }
// }
//代码走到此处,说明缓存中没有图片,需要到第三级缓存:网络缓存去取
//通过handler实现子线程和ui主线程的通信
final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bitmap bitmap = (Bitmap) msg.obj;
callBack.callBack(imgUrl,bitmap);
}
};
//启动线程访问图片
new Thread(){
@Override
public void run() {
super.run();
//加载图片
Bitmap bitmap = new NetWorkUtils().getBitmapByHttpUrlConnectionGet(imgUrl);
//压缩图片
//把bitmap缓存到缓存中,通过软引用
bitMaps.put(imgUrl,new SoftReference<Bitmap>(bitmap));
handler.sendMessage(handler.obtainMessage(1,bitmap));//发给handler
}
}.start();
// //内存中没有图片,通过次线程去加载,然后放在缓存中
// bitMaps.put(imgUrl,bitmap);
return null;
}
}
\ No newline at end of file
... ...
package com.wxwork.flutter_wxwork;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 网络请求的工具类
* Created by Administrator on 2017/9/1.
*/
public class NetWorkUtils {
//获得json串的方法,通过HttpClient get
public String getJsonByHttpClientGet(String url){
return "";
}
//获得json串的方法,通过HttpClient get
public String getJsonByHttpUrlConnectionGet(String jsonUrl){
URL url = null;
HttpURLConnection httpURLConnection = null;
String strJson = "";
InputStream inputStream = null;
try {
url = new URL(jsonUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if(responseCode == 200){
inputStream = httpURLConnection.getInputStream();
byte[] b = new byte[1024];
int length = 0;
while((length = inputStream.read(b)) != -1){//循环读取json串,拼装
strJson += new String(b,0,length);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return strJson;//返回最终的json数据
}
//获得json串的方法,通过HttpClient get
public Bitmap getBitmapByHttpUrlConnectionGet(String imageUrl){
URL url = null;
HttpURLConnection httpURLConnection = null;
Bitmap bitmap = null;
InputStream inputStream = null;
try {
url = new URL(imageUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if(responseCode == 200){
inputStream = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);//把图片信息(输入流)
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bitmap;//返回最终的json数据
}
}
\ No newline at end of file
... ...
... ... @@ -32,9 +32,10 @@ Future<bool> shareImagePath(String path) {
{String userName, //必须是应用关联的小程序,注意要有@app后缀
String path,
String hdImageData,
String title = "分享标题"}) {
String title = "分享标题",
String description = ""}) {
return FlutterWxworkPlatform.instance.shareMiniProgram(
userName: userName, path: path, hdImageData: hdImageData, title: title);
userName: userName, path: path, hdImageData: hdImageData, title: title,description:description);
}
Future<bool> shareText({String text = "分享内容"}) {
... ...
... ... @@ -60,13 +60,15 @@ class MethodChannelFlutterWxwork extends FlutterWxworkPlatform {
{String userName, //必须是应用关联的小程序,注意要有@app后缀
String path,
String hdImageData,
String title = "分享标题"}) async {
String title = "分享标题",
String description= ""}) async {
final shareMiniProgram = await methodChannel.invokeMethod<bool>(
'shareMiniProgram', <String, String>{
'userName': userName,
'path': path,
'hdImageData': hdImageData,
'title': title
'title': title,
"description":description
});
return shareMiniProgram;
}
... ...
... ... @@ -53,7 +53,8 @@ abstract class FlutterWxworkPlatform extends PlatformInterface {
{String userName, //必须是应用关联的小程序,注意要有@app后缀
String path,
String hdImageData,
String title = "分享标题"}) {
String title = "分享标题",
String description = ""}) {
throw UnimplementedError('shareMiniProgram() has not been implemented.');
}
... ...