微信图片选择分享完整demo:
1.调用微信官方api进行分享;
2.调用系统api进行微信分享;
3.支持分享到好友,群,朋友圈;
提供:
APP_ID (自己申请的,仅供测试使用,不作任何商业用途)
public static final String APP_ID = "wx2610542ce8ceee9a";
签名文件:
keyAlias 'ppshare'
keyPassword '111111'
注意:
1.要获得微信分享的回调必须在报名下的wxapi包中创建WXEntryActivity(Activity),并实现IWXAPIEventHandler接口进行回调,menifest中声明 android:exported=”true”
如下路径:
com.ppshare.ppshare.wxapi.WXEntryActivity
2.必须对apk进行签名;
3.包名要与申请appid时填写的一致;
具体参考demo
以下提供实现核心代码仅供参考:
/**
* @author wangjian
*/
public class WXEntryActivity extends Activity implements AdapterView.OnItemClickListener, IWXAPIEventHandler {
public static final int REQ_CAMERA = 2;
private static final int THUMB_SIZE = 150;
public GridView mImageGv;
private CheckBox isTimelineCb;
private EditText mTextEt;
// 用于图片选择模块
public List mFiles;
public FileItem mEmptyFile = new FileItem("");
public ImageAdapter mAdapter;
protected int mMaxPhotos = 10;
public List mDelList = new ArrayList<>();
// IWXAPI 是第三方app和微信通信的openapi接口
private IWXAPI api;
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
api.handleIntent(intent, this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
// 通过WXAPIFactory工厂,获取IWXAPI的实例
api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
isTimelineCb = (CheckBox) findViewById(R.id.is_timeline_cb);
mTextEt = (EditText) findViewById(R.id.et_text);
mImageGv = (GridView) findViewById(R.id.gv_image);
if (mImageGv != null) {
mImageGv.setOnItemClickListener(this);
}
if (mImageGv != null) {
mAdapter = new ImageAdapter();
mAdapter.setDataList(getFiles());
mImageGv.setAdapter(mAdapter);
}
// 注册微信分享回调
api.handleIntent(getIntent(), this);
}
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
if (parent instanceof GridView) {
if (position < mAdapter.getCount() - 1) {
FileItem item = mAdapter.getItem(position);
if (!TextUtils.isEmpty(item.id) && !mDelList.contains(item)) {
mDelList.add(item);
}
getFiles().remove(position);
onImageFileChanged();
}
else {
pickPicture(mMaxPhotos - getFiles().size());
}
}
}
/**
* 图片选择
*
* @param max 最大选择数,可自定义
*/
protected void pickPicture(int max) {
if (max <= 0) {
return;
}
Bundle bundle = new Bundle();
bundle.putInt(SelectPhotoActivity.EXTRA_MAX_PHOTO, max);
SelectPhotoActivity.go(null, this, REQ_CAMERA, bundle);
}
protected File[] getFile() {
if (getPics().size() <= 1) {
return null;
}
List pics = getPics();
File[] fs = new File[pics.size() - 1];
for (int i = 0; i < pics.size() - 1; i++) {
fs[i] = pics.get(i).getFile();
}
return fs;
}
/**
* 更新界面
*/
protected void onImageFileChanged() {
mAdapter.setDataList(getFiles());
mAdapter.notifyDataSetChanged();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQ_CAMERA && data != null) {
List list = (List) data.getSerializableExtra(Intent.EXTRA_RETURN_RESULT);
if (list != null) {
for (ImageItem imageItem : list) {
getFiles().add(new FileItem(imageItem));
}
}
onImageFileChanged();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public List getFiles() {
if (mFiles == null) {
mFiles = new ArrayList<>();
}
if (mFiles.contains(mEmptyFile)) {
mFiles.remove(mEmptyFile);
}
mFiles.add(mEmptyFile);
return mFiles;
}
public ArrayList getPics() {
ArrayList items = new ArrayList<>();
if (getFiles().size() > 1) {
for (FileItem item : getFiles()) {
if (!item.isUploaded()) {
items.add(item);
}
}
}
return items;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_send, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//当点击不同的menu item 是执行不同的操作
switch (id) {
case R.id.action_sure:
// String text = mTextEt.getText().toString();
// if (!TextUtils.isEmpty(text)) {
// shareText(text);
// }
if (getPics().size() > 0) {
shareImageAndText(getPics().get(0).path);
}
else {
Toast.makeText(this, "请选择一张图片", Toast.LENGTH_SHORT).show();
}
break;
case R.id.action_more:
// 调用多张图片分享时,需要传递多个图片的uri集合
if (getPics().size() > 0) {
ArrayList list = new ArrayList<>();
for (FileItem item1 : getPics()) {
File file = new File(item1.path);
if (file.exists()) {
// 获取图片uri
Uri uri = Uri.fromFile(file);
list.add(uri);
}
}
shareToFriend(list);
}
else {
Toast.makeText(this, "请选择一张图片", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/**
* 使用微信api分享文字
*
* @param text
*/
private void shareText(String text) {
// 初始化一个WXTextObject对象
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 = isTimelineCb.isChecked() ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
// 调用api接口发送数据到微信
api.sendReq(req);
}
/**
* 分享图片到微信
*
* @param path
*/
private void shareImageAndText(String path) {
// 初始化一个WXImageObject对象
WXImageObject imgObj = new WXImageObject();
imgObj.setImagePath(path);
// 用WXImageObject对象初始化一个WXMediaMessage对象
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = imgObj;
// 图片压缩
Bitmap bmp = BitmapFactory.decodeFile(path);
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 = isTimelineCb.isChecked() ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
boolean issend = api.sendReq(req);
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
/**
* 调用系统方法发送图片到微信
*
* @param list
*/
private void shareToFriend(ArrayList list) {
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("image/*");
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, list);
intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
intent.putExtra(Intent.EXTRA_TITLE, "图片分享");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(Intent.createChooser(intent, "请选择"));
}
// 微信发送请求到第三方应用时,会回调到该方法
@Override
public void onReq(BaseReq req) {
switch (req.getType()) {
case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
goToGetMsg();
break;
case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
goToShowMsg((ShowMessageFromWX.Req) req);
break;
default:
break;
}
}
// 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
@Override
public void onResp(BaseResp resp) {
int result = 0;
switch (resp.errCode) {
case BaseResp.ErrCode.ERR_OK:
result = R.string.errcode_success;
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
result = R.string.errcode_cancel;
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
result = R.string.errcode_deny;
break;
default:
result = R.string.errcode_unknown;
break;
}
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
private void goToGetMsg() {
Intent intent = new Intent(this, GetFromWXActivity.class);
intent.putExtras(getIntent());
startActivity(intent);
finish();
}
private void goToShowMsg(ShowMessageFromWX.Req showReq) {
WXMediaMessage wxMsg = showReq.message;
WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;
StringBuffer msg = new StringBuffer(); // 组织一个待显示的消息内容
msg.append("description: ");
msg.append(wxMsg.description);
msg.append("\n");
msg.append("extInfo: ");
msg.append(obj.extInfo);
msg.append("\n");
msg.append("filePath: ");
msg.append(obj.filePath);
Intent intent = new Intent(this, ShowFromWXActivity.class);
intent.putExtra(Constants.ShowMsgActivity.STitle, wxMsg.title);
intent.putExtra(Constants.ShowMsgActivity.SMessage, msg.toString());
intent.putExtra(Constants.ShowMsgActivity.BAThumbData, wxMsg.thumbData);
startActivity(intent);
finish();
}
protected static class FileItem implements java.io.Serializable {
private static final String SCHEMA_HTTP = "http://";
private static final String SCHEMA_FILE = "file://";
public String path;
public String id;
public File file;
public String thumb;
public FileItem(String path) {
this.path = path;
}
public FileItem(ImageItem item) {
this.path = item.imagePath;
this.thumb = item.thumbnailPath;
if (TextUtils.isEmpty(thumb)) {
this.thumb = item.imagePath;
}
}
public FileItem(String id, String path) {
this.path = path;
this.id = id;
}
public File getFile() {
if (file == null) {
file = new File(path);
}
return file;
}
public void setId(String id) {
this.id = id;
}
public boolean isUploaded() {
return !TextUtils.isEmpty(this.id) || (path.startsWith(SCHEMA_HTTP));
}
public String getUrl() {
if (isUploaded()) {
if (this.thumb.startsWith(SCHEMA_HTTP)) {
return this.thumb;
}
else {
return SCHEMA_HTTP + this.thumb;
}
}
else {
if (this.thumb.startsWith(SCHEMA_FILE)) {
return this.thumb;
}
else {
return SCHEMA_FILE + this.thumb;
}
}
}
}
public class ImageAdapter extends AfBaseAdapter {
@Override
public int getLayout() {
return R.layout.post_photo_item;
}
@Override
public void onUpdateView(View convertView, int position) {
Holder holder = (Holder) convertView.getTag();
if (holder == null) {
holder = new Holder();
holder.mDel = (ImageView) convertView.findViewById(R.id.iv_delete_icon);
holder.mImage = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(holder);
}
int count = getCount();
if (position == count - 1) {
holder.mDel.setVisibility(View.GONE);
holder.mImage.setImageResource(R.mipmap.bg_add_photo);
}
else {
FileItem item = getItem(position);
holder.mDel.setVisibility(View.VISIBLE);
if (TextUtils.isEmpty(item.id)) {
holder.mImage.setImageURI(Uri.parse(item.getUrl()));
}
else {
holder.mImage.setImageBitmap(BitmapFactory.decodeFile(item.path));
//Glide.with(PostActivity.this).load(item.path).into(holder.mImage);
}
}
}
@Override
public int getCount() {
return super.getCount();
}
}
private static class Holder {
public ImageView mImage;
public ImageView mDel;
}
}
以下是截图:
以下提供完整demo下载地址