游戏中里开发分享功能时用到两个小功能:1.复制一个链接到剪切板供在其他应用粘贴分享使用,2.保存一张二维码图像到相册供发送给其他应用用于分享。但是在unity中无法完成,需要分别开发相应的插件。
Android 部分:
使用android studio生成jar包(注意:其中
com.ztgame.ztmyseabed 为unity中playersettings里面设置的游戏bundle id
),
ClipboardTools.java 代码如下
package com.ztgame.ztmyseabed; //bundle id,建立工程时设置的包名 import android.app.Activity;
import android.content.ClipboardManager;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log; import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Field; /**
* Created by lanyantao on 2017/6/2.
*/
public class ClipboardTools {
public static ClipboardManager clipboard = null; // 向剪贴板中添加文本
public void copyTextToClipboard(final Context activity, final String str) throws Exception {
clipboard = (ClipboardManager) activity.getSystemService(Activity.CLIPBOARD_SERVICE);
ClipData textCd = ClipData.newPlainText("data", str);
clipboard.setPrimaryClip(textCd);
} // 从剪贴板中获取文本
public String getTextFromClipboard() {
if (clipboard != null && clipboard.hasPrimaryClip()
&& clipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
ClipData cdText = clipboard.getPrimaryClip();
ClipData.Item item = cdText.getItemAt(0);
return item.getText().toString();
}
return "null";
} public void SaveImageToGallery(final Context activity, final String path) {
try{
Context context = activity;
File file = new File(path); String url = "";
// 其次把文件插入到系统图库,(inserImgae中的参数没搞明白,第三个name这个参数不知道意义是什么,保存出来的的图像名称并不是这个name,而是系统按照时间生成的一个数字12496846464836.jpg这样,可否有人告知在下?)
try {
url = MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), file.getName(), null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} // 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath()))); }catch(Exception e)
{
Log.e("SaveImageToGallery", e.getMessage());
}
}
} //release库打包指令:gradlew assembleRelease,在Terminal中执行即可
打包jar包的时候,我直接生成没有release包,都是debug的jar,如果要生成release的jar,
release库打包指令:gradlew assembleRelease,在Terminal中执行即可,首次执行需要下载一些工具包,会比较慢 也可以直接使用我自己打包的jar文件,路径:http://files.cnblogs.com/files/lan-yt/jar.zip iOS 部分:
ShareUtil.h 头文件:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h> @ interface ShareUtilLib : NSObject extern "C"
{
/* 接口方法 */
void _SavePhoto(const char *readAddr);
void _copyTextToClipboard(const char *textList);
} - ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error
contextInfo: ( void *) contextInfo; @end
ShareUtil.mm 文件(ios中,.m文件为纯object-c语言,.mm文件为object-c和c++混合语言):
#import "ShareUtil.h" @implementation ShareUtilLib
//将文本复制到IOS剪贴板
- (void)objc_copyTextToClipboard : (NSString *)text
{
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = text;
} - ( void ) imageSaved: ( UIImage *) image didFinishSavingWithError:( NSError *)error
contextInfo: ( void *) contextInfo
{
if (error != nil) {
NSLog(@"二维码保存错误");
}
} @end extern "C" {
static ShareUtilLib *iosClipboard; void _copyTextToClipboard(const char *textList)
{
NSString *text = [NSString stringWithUTF8String: textList] ; if(iosClipboard == NULL)
{
iosClipboard = [[ShareUtilLib alloc] init];
} [iosClipboard objc_copyTextToClipboard: text];
} void _SavePhoto(const char *readAddr)
{
NSString *strReadAddr = [NSString stringWithUTF8String:readAddr];
UIImage *img = [UIImage imageWithContentsOfFile:strReadAddr];
//NSLog([NSString stringWithFormat:@"w:%f, h:%f", img.size.width, img.size.height]);
ShareUtilLib *instance = [ShareUtilLib alloc];
UIImageWriteToSavedPhotosAlbum(img, instance,
@selector(imageSaved:didFinishSavingWithError:contextInfo:), nil);
}
}
unity中使用:
android平台jar文件放在Assets\Plugins\Android下,ios平台直接将上述两页代码放在Assets\Plugins\iOS下
然后在C#调用
using UnityEngine;
using System.Runtime.InteropServices; namespace SDK.Lib
{
/**
* @brief 分享:复制文本到剪切板,保存图像到相册
*/
public class ShareUtil
{ #if UNITY_IOS
/* Interface to native implementation */
[DllImport ("__Internal")]
private static extern void _copyTextToClipboard(string text);
[DllImport ("__Internal")]
private static extern void _SavePhoto(string readAddr);
#endif public ShareUtil()
{ } public void init()
{ } public void dispose()
{ } //复制文本到剪切板
public void copy_text_to_clipboard(string str)
{
#if UNITY_IOS
this.copy_text_ios(str);
#elif UNITY_ANDROID
this.copy_text_android(str);
#endif
} private void copy_text_android(string str)
{
// "com.ztgame.ztmyseabed.ClipboardTools" : java中的类目录 + 类名
AndroidJavaObject androidObject = new AndroidJavaObject("com.ztgame.ztmyseabed.ClipboardTools");
AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
if (activity == null)
return; // 复制到剪贴板
androidObject.Call("copyTextToClipboard", activity, str); // 从剪贴板中获取文本
//string text = androidObject.Call<string>("getTextFromClipboard");
} private void copy_text_ios(string str)
{
#if UNITY_IOS
_copyTextToClipboard(str);
#endif
} //保存图像到相册
public void save_img_to_album()
{
string srcpath = Application.persistentDataPath + "/MyQrCode.png";
Ctx.mInstance.mQrCodeMgr.savePic(srcpath);//先自己保存二维码图片,这个在自己代码中先生成图像 #if UNITY_IOS
this.save_img_ios(srcpath);
#elif UNITY_ANDROID
this.save_img_android(srcpath);
#endif
} //unity中直接保存图片到sdcard,但是不会显示在相册中
private void save_img_android_by_unity(string srcpath)
{
MDataStream srcDataStream = new MDataStream(srcpath);
srcDataStream.open(); byte[] bytes = srcDataStream.readByte();
string destination = "/sdcard/DCIM/ztgame";
//判断目录是否存在,不存在则会创建目录
if (!System.IO.Directory.Exists(destination))
{
System.IO.Directory.CreateDirectory(destination);
}
string path_save = destination + "/myUFO.png";
//存图片
System.IO.File.WriteAllBytes(path_save, bytes); srcDataStream.dispose();
} private void save_img_android(string srcpath)
{
AndroidJavaObject androidObject = new AndroidJavaObject("com.ztgame.ztmyseabed.ClipboardTools");
AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
if (activity == null)
return; // 保存到相册
androidObject.Call("SaveImageToGallery", activity, srcpath);
} private void save_img_ios(string srcpath)
{
#if UNITY_IOS
_SavePhoto(srcpath);
#endif
}
}
}
注意:
iOS10以上的系统访问相册会崩溃,需要添加权限,参照 http://www.jianshu.com/p/e79156f80c22
另外:貌似有些andorid测试不成功,待研究 感谢参考文章:
http://www.cnblogs.com/xiaozefeng/p/Unity_Android_IOS.html
http://blog.csdn.net/st75033562/article/details/52597597
http://www.cnblogs.com/LzwBlog/p/5703590.html
http://blog.csdn.net/AnYuanLzh/article/details/50748928
等等。。。