提交 6b12b986 authored 作者: JarvanMo's avatar JarvanMo

rename to fluwx

上级 0f236174
# wechat_plugin
# fluwx
A Flutter plugin for wechat.
A new Flutter plugin for Wechat SDK.
## Getting Started
......
group 'com.jarvanmo.wechatplugin'
group 'com.jarvan.fluwx'
version '1.0-SNAPSHOT'
buildscript {
......@@ -9,7 +9,7 @@ buildscript {
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.4'
classpath 'com.android.tools.build:gradle:3.0.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
......
rootProject.name = 'wechat_plugin'
rootProject.name = 'fluwx'
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jarvanmo.wechatplugin">
<application>
<receiver
android:name=".AppRegister"
android:permission="com.tencent.mm.plugin.permission.SEND" >
<intent-filter>
<action android:name="com.tencent.mm.plugin.openapi.Intent.ACTION_REFRESH_WXAPP" />
</intent-filter>
</receiver>
</application>
package="com.jarvan.fluwx">
</manifest>
package com.jarvanmo.wechatplugin
package com.jarvan.fluwx
import com.jarvanmo.wechatplugin.constant.CallResult
import com.jarvanmo.wechatplugin.constant.WeChatPluginMethods
import com.jarvanmo.wechatplugin.handler.WeChatPluginHandler
import com.jarvan.fluwx.constant.CallResult
import com.jarvan.fluwx.constant.WeChatPluginMethods
import com.jarvan.fluwx.handler.WeChatPluginHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.PluginRegistry.Registrar
class WechatPlugin( private var registrar: Registrar) : MethodCallHandler {
class FluwxPlugin(private var registrar: Registrar) : MethodCallHandler {
companion object {
@JvmStatic
val TAG = "WeChatPlugin"
@JvmStatic
fun registerWith(registrar: Registrar): Unit {
val channel = MethodChannel(registrar.messenger(), "wechat_plugin")
val channel = MethodChannel(registrar.messenger(), "fluwx")
WeChatPluginHandler.setRegistrar(registrar)
channel.setMethodCallHandler(WechatPlugin(registrar))
WeChatPluginHandler.setMethodChannel(channel)
channel.setMethodCallHandler(FluwxPlugin(registrar))
}
}
override fun onMethodCall(call: MethodCall, result: Result): Unit {
when {
WeChatPluginMethods.INIT == call.method -> {
val api = WXAPIFactory.createWXAPI(registrar.context().applicationContext, call.arguments as String?)
......@@ -36,12 +32,9 @@ class WechatPlugin( private var registrar: Registrar) : MethodCallHandler {
result.error(CallResult.RESULT_API_NULL, "please config wxapi first", null)
return
}
call.method.startsWith("share")->{
call.method.startsWith("share") -> {
WeChatPluginHandler.handle(call, result)
}
}
}
}
package com.jarvan.fluwx.constant;
public class CallResult {
public static final String RESULT_DONE = "done";
public static final String RESULT_ERROR = "error";
public static final String RESULT_API_NULL = "wxapi not configured";
public static final String RESULT_WE_CHAT_NOT_INSTALLED = "wechat not installed";
public static final String RESULT_FILE_NOT_EXIST = "file not exists";
}
package com.jarvanmo.wechatplugin.constant;
package com.jarvan.fluwx.constant;
public class WeChatPluginImageSchema {
public static final String SCHEMA_ASSETS = "assets://";
......
package com.jarvan.fluwx.constant;
/***
* Created by mo on 2018/8/8
* 冷风如刀,以大地为砧板,视众生为鱼肉。
* 万里飞雪,将穹苍作烘炉,熔万物为白银。
**/
public class WeChatPluginMethods {
public static final String INIT = "initWeChat";
public static final String WE_CHAT_RESPONSE = "onWeChatResponse";
public static final String SHARE_TEXT = "shareText";
public static final String SHARE_IMAGE = "shareImage";
public static final String SHARE_MUSIC = "shareMusic";
public static final String SHARE_VIDEO = "shareVideo";
public static final String SHARE_WEB_PAGE = "shareWebPage";
public static final String SHARE_MINI_PROGRAM = "shareMiniProgram";
}
package com.jarvanmo.wechatplugin.handler
package com.jarvan.fluwx.handler
import com.jarvanmo.wechatplugin.constant.CallResult
import com.jarvanmo.wechatplugin.constant.WeChatPluginMethods
import com.jarvanmo.wechatplugin.constant.WechatPluginKeys
import com.jarvanmo.wechatplugin.utils.ShareImageUtil
import com.jarvanmo.wechatplugin.utils.WeChatThumbnailUtil
import com.jarvan.fluwx.constant.CallResult
import com.jarvan.fluwx.constant.WeChatPluginMethods
import com.jarvan.fluwx.constant.WechatPluginKeys
import com.jarvan.fluwx.utils.ShareImageUtil
import com.jarvan.fluwx.utils.WeChatThumbnailUtil
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.*
import com.tencent.mm.opensdk.openapi.IWXAPI
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.PluginRegistry
import android.R.id.message
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.jarvanmo.wechatplugin.utils.Util.bmpToByteArray
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.R.attr.description
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXMusicObject
/***
* Created by mo on 2018/8/8
* 冷风如刀,以大地为砧板,视众生为鱼肉。
......@@ -39,31 +33,31 @@ object WeChatPluginHandler {
fun apiIsNull() = wxApi == null
fun setMethodChannel(channel: MethodChannel) {
this.channel = channel
WeChatPluginHandler.channel = channel
}
fun setWxApi(wxApi: IWXAPI) {
this.wxApi = wxApi
WeChatPluginHandler.wxApi = wxApi
}
fun setRegistrar(registrar: PluginRegistry.Registrar) {
this.registrar = registrar
WeChatPluginHandler.registrar = registrar
}
fun handle(call: MethodCall, result: MethodChannel.Result) {
if (wxApi!!.isWXAppInstalled){
result.error(CallResult.RESULT_WE_CHAT_NOT_INSTALLED,CallResult.RESULT_WE_CHAT_NOT_INSTALLED,null)
if (wxApi!!.isWXAppInstalled) {
result.error(CallResult.RESULT_WE_CHAT_NOT_INSTALLED, CallResult.RESULT_WE_CHAT_NOT_INSTALLED, null)
return
}
when (call.method) {
WeChatPluginMethods.SHARE_TEXT -> shareText(call,result)
WeChatPluginMethods.SHARE_TEXT -> shareText(call, result)
WeChatPluginMethods.SHARE_MINI_PROGRAM -> shareMiniProgram(call, result)
WeChatPluginMethods.SHARE_IMAGE -> shareImage(call, result)
WeChatPluginMethods.SHARE_MUSIC -> shareMusic(call,result)
WeChatPluginMethods.SHARE_VIDEO -> shareVideo(call,result)
WeChatPluginMethods.SHARE_WEB_PAGE -> shareVideo(call,result)
WeChatPluginMethods.SHARE_MUSIC -> shareMusic(call, result)
WeChatPluginMethods.SHARE_VIDEO -> shareVideo(call, result)
WeChatPluginMethods.SHARE_WEB_PAGE -> shareVideo(call, result)
else -> {
result.notImplemented()
}
......@@ -78,7 +72,7 @@ object WeChatPluginHandler {
msg.description = call.argument(WechatPluginKeys.TEXT)
val req = SendMessageToWX.Req()
req.message = msg
setCommonArguments(call,req)
setCommonArguments(call, req)
wxApi?.sendReq(req)
result.success(true)
......@@ -114,15 +108,15 @@ object WeChatPluginHandler {
private fun shareImage(call: MethodCall, result: MethodChannel.Result) {
val imagePath = call.argument<String>(WechatPluginKeys.IMAGE)
val byteArray = ShareImageUtil.getImageData(registrar,imagePath)
val imgObj = if(byteArray != null){
val byteArray = ShareImageUtil.getImageData(registrar, imagePath)
val imgObj = if (byteArray != null) {
WXImageObject(byteArray)
}else{
} else {
null
}
if (imgObj == null) {
result.error(CallResult.RESULT_FILE_NOT_EXIST,CallResult.RESULT_FILE_NOT_EXIST,imagePath)
result.error(CallResult.RESULT_FILE_NOT_EXIST, CallResult.RESULT_FILE_NOT_EXIST, imagePath)
return
}
......@@ -131,27 +125,28 @@ object WeChatPluginHandler {
msg.thumbData = WeChatThumbnailUtil.thumbnailForCommon(call.argument(WechatPluginKeys.THUMBNAIL), registrar)
//
val req = SendMessageToWX.Req()
setCommonArguments(call,req)
setCommonArguments(call, req)
// req.message = msg
wxApi?.sendReq(req)
result.success(true)
}
private fun shareMusic(call: MethodCall, result: MethodChannel.Result) {
val music = WXMusicObject()
val musicUrl :String? = call.argument("musicUrl")
val musicLowBandUrl :String? = call.argument("musicLowBandUrl")
if (musicUrl != null){
val musicUrl: String? = call.argument("musicUrl")
val musicLowBandUrl: String? = call.argument("musicLowBandUrl")
if (musicUrl != null) {
music.musicUrl = musicUrl
}else{
} else {
music.musicLowBandUrl = musicLowBandUrl
}
val msg = WXMediaMessage()
msg.mediaObject = music
msg.title = call.argument("title")
msg.description = call.argument("description")
val thumbnail:String? = call.argument("thumbnail")
if(thumbnail != null && thumbnail.isNotBlank()){
msg.thumbData = WeChatThumbnailUtil.thumbnailForCommon(thumbnail,registrar)
val thumbnail: String? = call.argument("thumbnail")
if (thumbnail != null && thumbnail.isNotBlank()) {
msg.thumbData = WeChatThumbnailUtil.thumbnailForCommon(thumbnail, registrar)
}
val req = SendMessageToWX.Req()
......@@ -161,22 +156,22 @@ object WeChatPluginHandler {
result.success(true)
}
private fun shareVideo(call: MethodCall, result: MethodChannel.Result){
private fun shareVideo(call: MethodCall, result: MethodChannel.Result) {
val video = WXVideoObject()
val videoUrl :String? = call.argument("videoUrl")
val videoLowBandUrl :String? = call.argument("videoLowBandUrl")
if (videoUrl != null){
val videoUrl: String? = call.argument("videoUrl")
val videoLowBandUrl: String? = call.argument("videoLowBandUrl")
if (videoUrl != null) {
video.videoUrl = videoUrl
}else{
} else {
video.videoLowBandUrl = videoLowBandUrl
}
val msg = WXMediaMessage()
msg.mediaObject = video
msg.title = call.argument(WechatPluginKeys.TITLE)
msg.description = call.argument(WechatPluginKeys.DESCRIPTION)
val thumbnail:String? = call.argument(WechatPluginKeys.THUMBNAIL)
if(thumbnail != null && thumbnail.isNotBlank()){
msg.thumbData = WeChatThumbnailUtil.thumbnailForCommon(thumbnail,registrar)
val thumbnail: String? = call.argument(WechatPluginKeys.THUMBNAIL)
if (thumbnail != null && thumbnail.isNotBlank()) {
msg.thumbData = WeChatThumbnailUtil.thumbnailForCommon(thumbnail, registrar)
}
val req = SendMessageToWX.Req()
......@@ -187,7 +182,7 @@ object WeChatPluginHandler {
}
private fun shareWebPage(call: MethodCall, result: MethodChannel.Result){
private fun shareWebPage(call: MethodCall, result: MethodChannel.Result) {
val webPage = WXWebpageObject()
webPage.webpageUrl = call.argument("webPage")
val msg = WXMediaMessage()
......@@ -195,9 +190,9 @@ object WeChatPluginHandler {
msg.mediaObject = webPage
msg.title = call.argument(WechatPluginKeys.TITLE)
msg.description = call.argument(WechatPluginKeys.DESCRIPTION)
val thumbnail:String? = call.argument(WechatPluginKeys.THUMBNAIL)
if(thumbnail != null && thumbnail.isNotBlank()){
msg.thumbData = WeChatThumbnailUtil.thumbnailForCommon(thumbnail,registrar)
val thumbnail: String? = call.argument(WechatPluginKeys.THUMBNAIL)
if (thumbnail != null && thumbnail.isNotBlank()) {
msg.thumbData = WeChatThumbnailUtil.thumbnailForCommon(thumbnail, registrar)
}
val req = SendMessageToWX.Req()
......@@ -207,7 +202,7 @@ object WeChatPluginHandler {
result.success(true)
}
// private fun createWxImageObject(imagePath:String):WXImageObject?{
// private fun createWxImageObject(imagePath:String):WXImageObject?{
// var imgObj: WXImageObject? = null
// var imageFile:File? = null
// if (imagePath.startsWith(WeChatPluginImageSchema.SCHEMA_ASSETS)){
......
package com.jarvanmo.wechatplugin.utils;
package com.jarvan.fluwx.utils;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
......@@ -8,7 +8,7 @@ import java.io.IOException;
import io.flutter.plugin.common.PluginRegistry;
public final class AssetManagerUtil {
private AssetManagerUtil(){
private AssetManagerUtil() {
throw new RuntimeException("can't do this");
}
......
package com.jarvanmo.wechatplugin.utils;
package com.jarvan.fluwx.utils;
import android.content.Context;
......@@ -10,16 +10,17 @@ import java.util.List;
import top.zibin.luban.Luban;
class CompressImageUtil {
private CompressImageUtil(){}
private CompressImageUtil() {
}
public static File compressUtilSmallerThan(int size,File file,Context context){
public static File compressUtilSmallerThan(int size, File file, Context context) {
File result = null;
File tmp = file;
List<File> dirtyFiles = new ArrayList<>();
try {
while (tmp.length() > size * 1024){
while (tmp.length() > size * 1024) {
List<File> compressedFiles = Luban.with(context)
.ignoreBy(size)
.load(tmp)
......@@ -36,7 +37,7 @@ class CompressImageUtil {
}
for (File dirtyFile : dirtyFiles) {
if(dirtyFile != result){
if (dirtyFile != result) {
dirtyFile.delete();
}
}
......
package com.jarvanmo.wechatplugin.utils;
package com.jarvan.fluwx.utils;
import android.content.res.AssetFileDescriptor;
......@@ -13,24 +13,24 @@ import okio.Okio;
import okio.Source;
public class FileUtil {
public static File createTmpFile(AssetFileDescriptor fileDescriptor ){
public static File createTmpFile(AssetFileDescriptor fileDescriptor) {
if (fileDescriptor == null) {
return null;
}
File file = null;
BufferedSink sink = null;
Source source= null;
Source source = null;
OutputStream outputStream = null;
try {
file = File.createTempFile(UUID.randomUUID().toString(),".png");
file = File.createTempFile(UUID.randomUUID().toString(), ".png");
outputStream = new FileOutputStream(file);
sink = Okio.buffer(Okio.sink(outputStream));
source = Okio.source(fileDescriptor.createInputStream());
sink.writeAll(source);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(sink != null){
} finally {
if (sink != null) {
try {
sink.close();
} catch (IOException e) {
......
package com.jarvanmo.wechatplugin.utils;
package com.jarvan.fluwx.utils;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.jarvanmo.wechatplugin.constant.WeChatPluginImageSchema;
import com.jarvanmo.wechatplugin.constant.WechatPluginKeys;
import com.jarvan.fluwx.constant.WeChatPluginImageSchema;
import com.jarvan.fluwx.constant.WechatPluginKeys;
import java.io.IOException;
import java.io.InputStream;
......@@ -44,11 +45,12 @@ public class ShareImageUtil {
return result;
}
private static byte[] streamToByteArray(InputStream inputStream){
private static byte[] streamToByteArray(InputStream inputStream) {
Bitmap bmp = null;
bmp = BitmapFactory.decodeStream(inputStream);
return Util.bmpToByteArray(bmp, true);
}
private static String getPackage(String assetsName) {
String packageStr = null;
if (assetsName.contains(WechatPluginKeys.PACKAGE)) {
......@@ -58,15 +60,15 @@ public class ShareImageUtil {
return packageStr;
}
private static InputStream openStream(String url){
private static InputStream openStream(String url) {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request request = new Request.Builder().url(url).get().build();
try {
Response response = okHttpClient.newCall(request).execute();
ResponseBody responseBody = response.body();
if(response.isSuccessful() && responseBody!= null){
if (response.isSuccessful() && responseBody != null) {
return responseBody.byteStream();
}else {
} else {
return null;
}
......
package com.jarvan.fluwx.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import junit.framework.Assert;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;
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(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;
}
}
package com.jarvanmo.wechatplugin.utils;
package com.jarvan.fluwx.utils;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.jarvanmo.wechatplugin.constant.WeChatPluginImageSchema;
import com.jarvanmo.wechatplugin.constant.WechatPluginKeys;
import com.jarvan.fluwx.constant.WeChatPluginImageSchema;
import com.jarvan.fluwx.constant.WechatPluginKeys;
import java.io.File;
import java.io.IOException;
......@@ -141,15 +142,15 @@ public class WeChatThumbnailUtil {
return packageStr;
}
private static InputStream openStream(String url){
private static InputStream openStream(String url) {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request request = new Request.Builder().url(url).get().build();
try {
Response response = okHttpClient.newCall(request).execute();
ResponseBody responseBody = response.body();
if(response.isSuccessful() && responseBody!= null){
if (response.isSuccessful() && responseBody != null) {
return responseBody.byteStream();
}else {
} else {
return null;
}
......
package com.jarvanmo.wechatplugin.constant;
public class CallResult {
public static final String RESULT_DONE = "done";
public static final String RESULT_ERROR = "error";
public static final String RESULT_API_NULL = "wxapi not configured";
public static final String RESULT_WE_CHAT_NOT_INSTALLED = "wechat not installed";
public static final String RESULT_FILE_NOT_EXIST = "file not exists";
}
package com.jarvanmo.wechatplugin.constant;
/***
* Created by mo on 2018/8/8
* 冷风如刀,以大地为砧板,视众生为鱼肉。
* 万里飞雪,将穹苍作烘炉,熔万物为白银。
**/
public class WeChatPluginMethods {
public static final String INIT ="initWeChat";
public static final String WE_CHAT_RESPONSE= "onWeChatResponse";
public static final String SHARE_TEXT = "shareText";
public static final String SHARE_IMAGE = "shareImage";
public static final String SHARE_MUSIC = "shareMusic";
public static final String SHARE_VIDEO ="shareVideo";
public static final String SHARE_WEB_PAGE = "shareWebPage";
public static final String SHARE_MINI_PROGRAM = "shareMiniProgram";
}
package com.jarvanmo.wechatplugin.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import junit.framework.Assert;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;
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(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;
}
}
# wechat_plugin_example
# fluwx_example
Demonstrates how to use the wechat_plugin plugin.
Demonstrates how to use the fluwx plugin.
## Getting Started
......
......@@ -27,7 +27,8 @@ android {
}
defaultConfig {
applicationId "net.sourceforge.simcpux"
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.jarvan.fluwxexample"
minSdkVersion 16
targetSdkVersion 27
versionCode 1
......
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jarvanmo.wechatpluginexample">
package="com.jarvan.fluwxexample">
<!-- The INTERNET permission is required for development. Specifically,
flutter needs it to communicate with the running application
......@@ -14,7 +14,7 @@
FlutterApplication and put your custom class here. -->
<application
android:name="io.flutter.app.FlutterApplication"
android:label="wechat_plugin_example"
android:label="fluwx_example"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
......
#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "Generated.xcconfig"
#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "Generated.xcconfig"
# Uncomment this line to define a global platform for your project
platform :ios, '9.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
def parse_KV_file(file, separator='=')
file_abs_path = File.expand_path(file)
if !File.exists? file_abs_path
return [];
end
pods_ary = []
skip_line_start_symbols = ["#", "/"]
File.foreach(file_abs_path) { |line|
next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
plugin = line.split(pattern=separator)
if plugin.length == 2
podname = plugin[0].strip()
path = plugin[1].strip()
podpath = File.expand_path("#{path}", file_abs_path)
pods_ary.push({:name => podname, :path => podpath});
else
puts "Invalid plugin specification: #{line}"
end
}
return pods_ary
end
target 'Runner' do
use_frameworks!
# Prepare symlinks folder. We use symlinks to avoid having Podfile.lock
# referring to absolute paths on developers' machines.
system('rm -rf .symlinks')
system('mkdir -p .symlinks/plugins')
# Flutter Pods
generated_xcode_build_settings = parse_KV_file('./Flutter/Generated.xcconfig')
if generated_xcode_build_settings.empty?
puts "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter packages get is executed first."
end
generated_xcode_build_settings.map { |p|
if p[:name] == 'FLUTTER_FRAMEWORK_DIR'
symlink = File.join('.symlinks', 'flutter')
File.symlink(File.dirname(p[:path]), symlink)
pod 'Flutter', :path => File.join(symlink, File.basename(p[:path]))
end
}
# Plugin Pods
plugin_pods = parse_KV_file('../.flutter-plugins')
plugin_pods.map { |p|
symlink = File.join('.symlinks', 'plugins', p[:name])
File.symlink(p[:path], symlink)
pod p[:name], :path => File.join(symlink, 'ios')
}
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['ENABLE_BITCODE'] = 'NO'
end
end
end
pod 'WechatOpenSDK'
PODS:
- Flutter (1.0.0)
- wechat_plugin (0.0.1):
- Flutter
- WechatOpenSDK (~> 1.8.2)
- WechatOpenSDK (1.8.2)
DEPENDENCIES:
- Flutter (from `.symlinks/flutter/ios`)
- wechat_plugin (from `.symlinks/plugins/wechat_plugin/ios`)
- WechatOpenSDK
SPEC REPOS:
https://github.com/cocoapods/specs.git:
- WechatOpenSDK
EXTERNAL SOURCES:
Flutter:
:path: ".symlinks/flutter/ios"
wechat_plugin:
:path: ".symlinks/plugins/wechat_plugin/ios"
SPEC CHECKSUMS:
Flutter: 9d0fac939486c9aba2809b7982dfdbb47a7b0296
wechat_plugin: 101a04e102a362bdc87af3abf66a094cd654d926
WechatOpenSDK: 676feec516a11173eafd1fe64b10d27babf28701
PODFILE CHECKSUM: 9663ba55aa377eec5ca2be16d9a7ad86f8d88698
COCOAPODS: 1.5.3
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0940"
LastUpgradeVersion = "0910"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
......@@ -26,6 +26,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
......@@ -45,6 +46,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
......
......@@ -4,7 +4,4 @@
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
#import <Flutter/Flutter.h>
#import <UIKit/UIKit.h>
@interface AppDelegate : FlutterAppDelegate
@end
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate,WXApiDelegate{
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
......@@ -11,7 +11,7 @@
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>wechat_plugin_example</string>
<string>fluwx_example</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
......@@ -41,16 +41,5 @@
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>weixin</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict>
</dict>
</plist>
@import UIKit; //使用1.6版必须有(PS:1.5版可以不要)
#import "WXApiObject.h"
#import "WXApi.h"
#import "GeneratedPluginRegistrant.h"
//
// WechatPlugin-Bridging-Header.h
// Runner
//
// Created by mo on 2018/8/8.
// Copyright © 2018年 The Chromium Authors. All rights reserved.
//
#ifndef WechatPlugin_Bridging_Header_h
#define WechatPlugin_Bridging_Header_h
@import UIKit; //使用1.6版必须有(PS:1.5版可以不要)
#import "WXApiObject.h"
#import "WXApi.h"
#endif /* WechatPlugin_Bridging_Header_h */
//
// WechatPluginMethods.swift
// Runner
//
// Created by mo on 2018/8/8.
// Copyright © 2018年 The Chromium Authors. All rights reserved.
//
import Foundation
struct WechatPluginMethods {
public static let SHARE_TEXT = "share_text";
public static let SHARE_IMAGE = "share_image";
public static let SHARE_MUSIC = "share_music";
public static let SHARE_VIDEO = "share_video";
public static let SHARE_WEBSITE = "share_website";
}
#import <Flutter/Flutter.h>
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char* argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wechat_plugin/fluwx.dart';
import 'package:fluwx/fluwx.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
//wxd930ea5d5a258f4f
@override
void initState() {
super.initState();
initPlatformState();
Fluwx.init("wxd930ea5d5a258f4f");
}
// Platform messages are asynchronous, so we initialize in an async method.
......@@ -28,7 +25,7 @@ class _MyAppState extends State<MyApp> {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
// platformVersion = await WechatPlugin.platformVersion;
// platformVersion = await Fluwx.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
......@@ -51,14 +48,7 @@ class _MyAppState extends State<MyApp> {
title: const Text('Plugin example app'),
),
body: new Center(
child: GestureDetector(
onTap:(){
var fluwx =Fluwx();
fluwx.shareText(WeChatShareTextModel(text: "wq kcg r",
transaction: "xxxx${DateTime.now().millisecondsSinceEpoch}",
));
} ,
child: new Text('Running on: $_platformVersion\n')),
child: new Text('Running on: $_platformVersion\n'),
),
),
);
......
name: wechat_plugin_example
description: Demonstrates how to use the wechat_plugin plugin.
name: fluwx_example
description: Demonstrates how to use the fluwx plugin.
dependencies:
flutter:
......@@ -13,7 +13,7 @@ dev_dependencies:
flutter_test:
sdk: flutter
wechat_plugin:
fluwx:
path: ../
# For information on the generic Dart part of this file, see the
......
......@@ -7,7 +7,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:wechat_plugin_example/main.dart';
import 'package:fluwx_example/main.dart';
void main() {
testWidgets('Verify Platform version', (WidgetTester tester) async {
......
{
"editor.quickSuggestions": false
}
\ No newline at end of file
//
// Bridging-Header.h
// wechat_plugin
//
// Created by mo on 2018/8/13.
//
#ifndef Bridging_Header_h
#define Bridging_Header_h
@import UIKit; //使用1.6版必须有(PS:1.5版可以不要)
#import "WXApiObject.h"
#import "WXApi.h"
#endif /* Bridging_Header_h */
#import <Flutter/Flutter.h>
@interface WechatPlugin : NSObject<FlutterPlugin>
@interface FluwxPlugin : NSObject<FlutterPlugin>
@end
#import "FluwxPlugin.h"
@implementation FluwxPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
FlutterMethodChannel* channel = [FlutterMethodChannel
methodChannelWithName:@"fluwx"
binaryMessenger:[registrar messenger]];
FluwxPlugin* instance = [[FluwxPlugin alloc] init];
[registrar addMethodCallDelegate:instance channel:channel];
}
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
if ([@"getPlatformVersion" isEqualToString:call.method]) {
result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
} else {
result(FlutterMethodNotImplemented);
}
}
@end
import Flutter
import UIKit
import wechat_plugin
public class SwiftWechatPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "wechat_plugin", binaryMessenger: registrar.messenger())
let instance = SwiftWechatPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case WeChatPluginMethods.SHARE_TEXT:
print("hh")
break;
default:
print("hh")
}
}
}
//
// WeChatPluginMethods.swift
// Pods-Runner
//
// Created by mo on 2018/8/10.
//
import Foundation
public class WeChatPluginMethods{
public static let SHARE_TEXT = "shareText";
public static let SHARE_IMAGE = "shareImage";
public static let SHARE_MUSIC = "shareMusic";
public static let SHARE_VIDEO = "shareVideo";
public static let SHARE_WEBSITE = "shareWebsite";
}
#import "WechatPlugin.h"
#import <wechat_plugin/wechat_plugin-Swift.h>
@implementation WechatPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
[SwiftWechatPlugin registerWithRegistrar:registrar];
}
@end
import Flutter
public class WeChatHandler {
static let instance:WeChatHandler = WeChatHandler()
public func shareText(call:FlutterMethodCall){
}
}
//
// H.swift
// Pods-Runner
//
// Created by mo on 2018/8/10.
//
import Foundation
......@@ -2,11 +2,11 @@
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'wechat_plugin'
s.name = 'fluwx'
s.version = '0.0.1'
s.summary = 'A Flutter plugin for wechat.'
s.summary = 'A new Flutter plugin for Wechat SDK.'
s.description = <<-DESC
A Flutter plugin for wechat.
A new Flutter plugin for Wechat SDK.
DESC
s.homepage = 'http://example.com'
s.license = { :file => '../LICENSE' }
......@@ -14,10 +14,7 @@ A Flutter plugin for wechat.
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.public_header_files = 'Classes/**/*.h'
s.static_framework = true
s.dependency 'Flutter'
s.dependency 'WechatOpenSDK', '~> 1.8.2'
s.ios.deployment_target = '8.0'
end
......
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:wechat_plugin/src/wechat_share_models.dart';
import 'package:fluwx/src/wechat_share_models.dart';
class Fluwx {
......
name: wechat_plugin
description: A Flutter plugin for wechat.
name: fluwx
description: A new Flutter plugin for Wechat SDK.
version: 0.0.1
author:
homepage:
......@@ -14,8 +14,8 @@ dependencies:
# The following section is specific to Flutter.
flutter:
plugin:
androidPackage: com.jarvanmo.wechatplugin
pluginClass: WechatPlugin
androidPackage: com.jarvan.fluwx
pluginClass: FluwxPlugin
# To add assets to your plugin package, add an assets section, like this:
# assets:
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论