这周末学习了如何将图片,文本,分享到微信好友或者是朋友圈,自己亲手敲了一把。结果一个bug让我很不爽。待会来谈谈bug是什么。
好了,写代码之前必须做这几件事情。在微信开发者网站上注册账号,填写app名称,包名,应用签名。第三个应用签名本以为自己随便写一个,其实不然,需要下载签名生成工具,然后安装到手机上(此为我的愚蠢Bug,后来看微信官网才解决了),还需要下载Android开发工具包,里面有个jar包需要导入到Android Studio中。注意,申请ok后会展示:
下面演示下Demo:
先来展示下布局效果吧:
再来看一下工程目录:
话说,展示效果也他妈太大了吧。
代码如下:
public class MainActivity extends Activity {
private IWXAPI api;
private CheckBox mCheckBox;
private static final String App_ID = "wxbb5a317744264a34";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
api = WXAPIFactory.createWXAPI(this, App_ID);
//注册ID
api.registerApp(App_ID);
mCheckBox = (CheckBox) findViewById(R.id.checkBox);
}
//启动微信客户端
public void btn_open_weixin(View view) {
//唯一标识符,采用text+当前时间{
//开启微信
api.openWXApp();
}
//生成唯一标识符
public String onlySign(final String text) {
//当前时间+字符串
return (text == null ? String.valueOf(System.currentTimeMillis()) : String.valueOf(text + System.currentTimeMillis()));
}
public void btn_send(View view) {
//分享文本到好友或者朋友圈,如果checkbox未选中,则发送给好友,否则,发送到朋友圈。
//创建EditText
final EditText mEditText = new EditText(this);
mEditText.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
mEditText.setText("默认的分享的文本");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher);
builder.setTitle("分享");
builder.setMessage("请输入要分享的文本");
builder.setView(mEditText);
builder.setPositiveButton("分享", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//获取要分享的内容
String text = mEditText.getText().toString();
if (text == null || text.length() == 0) {
return;
}
//第一步:创建WXTextObject对象,用于封装text
WXTextObject object = new WXTextObject();
object.text = text;
//第二步:拿到WXMediaMessage对象,用于客户端向微信发送数据
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = object;
msg.description = text;
//第三步:拿到SendMessageToWX.Req对象,用于请求微信客户端
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.message = msg;
//生成唯一标识符
req.transaction = onlySign("text");
//建立场景,到底是发送给朋友还是朋友圈
req.scene = mCheckBox.isChecked() ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
//这次真的发送了
Toast.makeText(MainActivity.this, String.valueOf(api.sendReq(req)), Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("取消", null);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
//将Bitmap装换成Byte数组,用来压缩图片
private byte[] BmpToByteArray(final Bitmap bitmap, final boolean isRecycle) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
if (isRecycle) {
bitmap.recycle();
}
byte[] result = outputStream.toByteArray();
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
//发送二进制图片
public void btn_send_binary_image(View view) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.robot);
WXImageObject object = new WXImageObject(bitmap);
WXMediaMessage message = new WXMediaMessage();
message.mediaObject = object;
Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 80, 80, true);
bitmap.recycle();
message.thumbData = BmpToByteArray(thumbBmp, true);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.message = message;
req.scene = mCheckBox.isChecked() ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
req.transaction = onlySign("BinaryImage");
Toast.makeText(MainActivity.this, String.valueOf(api.sendReq(req)), Toast.LENGTH_LONG).show();
}
public void btn_send_local_Image(View view) {
String path = "/sdcard/1461370355308.jpeg";
File file = new File(path);
if (!file.exists()) {
Toast.makeText(this, "图片不存在", Toast.LENGTH_LONG).show();
return;
}
WXImageObject object = new WXImageObject();
object.setImagePath(path);
WXMediaMessage message = new WXMediaMessage();
message.mediaObject = object;
Bitmap bitmap = BitmapFactory.decodeFile(path);
Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 80, 80, true);
bitmap.recycle();
message.thumbData = BmpToByteArray(thumbBmp, true);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.message = message;
req.scene = mCheckBox.isChecked() ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
req.transaction = onlySign("LocalImage");
Toast.makeText(MainActivity.this, String.valueOf(api.sendReq(req)), Toast.LENGTH_LONG).show();
}
public void btn_send_Internet_image(View view) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
String uri = "http://img1.imgtn.bdimg.com/it/u=2468413383,2378712674&fm=21&gp=0.jpg";
WXImageObject object = new WXImageObject();
// object.imageUrl = uri;
object.setImagePath(uri);
WXMediaMessage message = new WXMediaMessage();
message.mediaObject =object;
Bitmap bitmap =BitmapFactory.decodeStream(new URL(uri).openStream());
Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap,80,80,true);
bitmap.recycle();
message.thumbData = BmpToByteArray(thumbBmp,true);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.message = message;
req.scene = mCheckBox.isChecked()?SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
req.transaction = onlySign("URLImage");
Toast.makeText(MainActivity.this,String.valueOf(api.sendReq(req)),Toast.LENGTH_LONG).show();
}catch (Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
}
public void btn_send_audio(View view){
WXMusicObject object =new WXMusicObject();
object.musicUrl = "http://music.baidu.com/song/290008";
WXMediaMessage msg = new WXMediaMessage();
msg.title="我只在乎你";
msg.description="演唱者:邓丽君";
msg.mediaObject = object;
Bitmap thumbBit = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
msg.thumbData = BmpToByteArray(thumbBit,true);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.message = msg;
req.scene = mCheckBox.isChecked()?SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
req.transaction = onlySign("URLAudio");
Toast.makeText(MainActivity.this,String.valueOf(api.sendReq(req)),Toast.LENGTH_LONG).show();
}
public void btn_send_video(View view){
WXVideoObject object = new WXVideoObject();
object.videoUrl="http://open.163.com/movie/2016/4/C/K/MBJEDVIOI_MBJEE9UCK.html";
WXMediaMessage msg = new WXMediaMessage();
msg.title="一切只需十分钟的专注";
msg.description="TED";
msg.mediaObject = object;
Bitmap thumbBit = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
msg.thumbData = BmpToByteArray(thumbBit,true);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.message = msg;
req.scene = mCheckBox.isChecked()?SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
req.transaction = onlySign("URLvideo");
Toast.makeText(MainActivity.this,String.valueOf(api.sendReq(req)),Toast.LENGTH_LONG).show();
}
public void btn_share_weburi(View view){
WXWebpageObject object = new WXWebpageObject();
object.webpageUrl ="http://open.163.com/ted/";
WXMediaMessage msg = new WXMediaMessage();
msg.title="网易公开课";
msg.description="TED";
msg.mediaObject = object;
Bitmap thumbBit = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
msg.thumbData = BmpToByteArray(thumbBit,true);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.message = msg;
req.scene = mCheckBox.isChecked()?SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
req.transaction = onlySign("WEBuri");
Toast.makeText(MainActivity.this,String.valueOf(api.sendReq(req)),Toast.LENGTH_LONG).show();
}
}
这里代码比较多,但都是差不多的,就创建对象时几个sdk不太一样罢了。这里其实可以将相同代码封装在方法中。更有维护性与可阅读性。
最后,展示下一部分效果吧
对于初学者来说或许会有一点问题,比如api.sendReq(req)明明返回true,可是没有调起微信朋友圈,或者分享图片时同样掉不起来,那么这时需要查清楚包名,APPID,应用签名是否一致,缩略图大小不能超过32k。如果再有问题欢迎留言或者推荐看这套视频(李宁微信分享)[http://www.imooc.com/learn/455].