Android应用中如何接入微信分享功能

Android应用中如何接入微信分享功能

本文小编为大家详细介绍“Android应用中如何接入微信分享功能”,内容详细,步骤清晰,细节处理妥当,希望这篇“Android应用中如何接入微信分享功能”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

注册应用信息并下载必要工具

Android应用中如何接入微信分享功能

  1. 在微信开放平台注册应用信息

  2. 下载 签名生成工具获取待接入应用的签名

  3. 应用信息填入签名

注意:由于一般调试签名和正式签名不一致,测试时可填入测试包的签名,上线时需要改为正式包的签名

接入

在build.gradle中,添加如下依赖:

dependencies{compile'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'}

或:

dependencies{compile'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'}

其中,前者包含统计功能

AndroidManifest.xml中添加权限和微信回调Activity

<uses-permissionandroid:name="android.permission.INTERNET"/><uses-permissionandroid:name="android.permission.MODIFY_AUDIO_SETTINGS"/><uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/><!--formtastatistics--><uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"/><uses-permissionandroid:name="android.permission.READ_PHONE_STATE"/><uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/><activityandroid:name=".WXEntryActivity"android:exported="true"android:screenOrientation="portrait"android:theme="@style/AppTheme.Fullscreen.Translucent"/>

这里使用了一个透明的Activity来处理微信分享结果回调

主题:

<stylename="AppTheme.Fullscreen"parent="Theme.AppCompat.NoActionBar"><itemname="android:windowNoTitle">true</item><itemname="android:windowFullscreen">true</item><itemname="android:windowTranslucentNavigation"tools:targetApi="kitkat">true</item></style><stylename="AppTheme.Fullscreen.Translucent"><itemname="android:windowBackground">@android:color/transparent</item><itemname="android:windowIsTranslucent">true</item><itemname="android:windowAnimationStyle">@android:style/Animation.Translucent</item></style>

Activity

当微信分享成功,点击返回App时,微信会主动调用WXEntryActivity,并将结果通过Intent传给WXEntryActivity,此时调用api.handleIntent(getIntent(), this)对结果进行处理,handleIntent第二个参数为IWXAPIEventHandler,分享结果会在onResp方法中处理,在这里我们发送一个广播,并在WXShare对象中对该广播进行监听

publicclassWXEntryActivityextendsBaseActivityimplementsIWXAPIEventHandler{privateIWXAPIapi;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);Logger.i("WXEntryActivity");WXShareshare=newWXShare(this);api=share//.register().getApi();//注意://第三方开发者如果使用透明界面来实现WXEntryActivity,需要判断handleIntent的返回值,如果返回值为false,则说明入参不合法未被SDK处理,应finish当前透明界面,避免外部通过传递非法参数的Intent导致停留在透明界面,引起用户的疑惑try{if(!api.handleIntent(getIntent(),this)){finish();}}catch(Exceptione){e.printStackTrace();}}@OverrideprotectedvoidonNewIntent(Intentintent){super.onNewIntent(intent);Logger.i("onNewIntent");setIntent(intent);if(!api.handleIntent(intent,this)){finish();}}@OverridepublicvoidonReq(BaseReqbaseReq){}@OverridepublicvoidonResp(BaseRespbaseResp){Intentintent=newIntent(WXShare.ACTION_SHARE_RESPONSE);intent.putExtra(WXShare.EXTRA_RESULT,newWXShare.Response(baseResp));sendBroadcast(intent);finish();}}

工具类

publicclassWXShare{publicstaticfinalStringAPP_ID="wx0123456789";publicstaticfinalStringACTION_SHARE_RESPONSE="action_wx_share_response";publicstaticfinalStringEXTRA_RESULT="result";privatefinalContextcontext;privatefinalIWXAPIapi;privateOnResponseListenerlistener;privateResponseReceiverreceiver;publicWXShare(Contextcontext){api=WXAPIFactory.createWXAPI(context,APP_ID);this.context=context;}publicWXShareregister(){//微信分享api.registerApp(APP_ID);receiver=newResponseReceiver();IntentFilterfilter=newIntentFilter(ACTION_SHARE_RESPONSE);context.registerReceiver(receiver,filter);returnthis;}publicvoidunregister(){try{api.unregisterApp();context.unregisterReceiver(receiver);}catch(Exceptione){e.printStackTrace();}}publicWXShareshare(Stringtext){WXTextObjecttextObj=newWXTextObject();textObj.text=text;WXMediaMessagemsg=newWXMediaMessage();msg.mediaObject=textObj;//msg.title="Willbeignored";msg.description=text;SendMessageToWX.Reqreq=newSendMessageToWX.Req();req.transaction=buildTransaction("text");req.message=msg;req.scene=SendMessageToWX.Req.WXSceneSession;booleanresult=api.sendReq(req);Logger.i("textshared:"+result);returnthis;}publicIWXAPIgetApi(){returnapi;}publicvoidsetListener(OnResponseListenerlistener){this.listener=listener;}privateStringbuildTransaction(finalStringtype){return(type==null)?String.valueOf(System.currentTimeMillis()):type+System.currentTimeMillis();}privateclassResponseReceiverextendsBroadcastReceiver{@OverridepublicvoidonReceive(Contextcontext,Intentintent){Responseresponse=intent.getParcelableExtra(EXTRA_RESULT);Logger.d("type:"+response.getType());Logger.d("errCode:"+response.errCode);Stringresult;if(listener!=null){if(response.errCode==BaseResp.ErrCode.ERR_OK){listener.onSuccess();}elseif(response.errCode==BaseResp.ErrCode.ERR_USER_CANCEL){listener.onCancel();}else{switch(response.errCode){caseBaseResp.ErrCode.ERR_AUTH_DENIED:result="发送被拒绝";break;caseBaseResp.ErrCode.ERR_UNSUPPORT:result="不支持错误";break;default:result="发送返回";break;}listener.onFail(result);}}}}publicstaticclassResponseextendsBaseRespimplementsParcelable{publicinterrCode;publicStringerrStr;publicStringtransaction;publicStringopenId;privateinttype;privatebooleancheckResult;publicResponse(BaseRespbaseResp){errCode=baseResp.errCode;errStr=baseResp.errStr;transaction=baseResp.transaction;openId=baseResp.openId;type=baseResp.getType();checkResult=baseResp.checkArgs();}@OverridepublicintgetType(){returntype;}@OverridepublicbooleancheckArgs(){returncheckResult;}@OverridepublicintdescribeContents(){return0;}@OverridepublicvoidwriteToParcel(Parceldest,intflags){dest.writeInt(this.errCode);dest.writeString(this.errStr);dest.writeString(this.transaction);dest.writeString(this.openId);dest.writeInt(this.type);dest.writeByte(this.checkResult?(byte)1:(byte)0);}protectedResponse(Parcelin){this.errCode=in.readInt();this.errStr=in.readString();this.transaction=in.readString();this.openId=in.readString();this.type=in.readInt();this.checkResult=in.readByte()!=0;}publicstaticfinalCreator<Response>CREATOR=newCreator<Response>(){@OverridepublicResponsecreateFromParcel(Parcelsource){returnnewResponse(source);}@OverridepublicResponse[]newArray(intsize){returnnewResponse[size];}};}}

接口

publicinterfaceOnResponseListener{voidonSuccess();voidonCancel();voidonFail(Stringmessage);}

使用

在需要使用微信分享的Activity中:

@OverrideprotectedvoidonCreate(BundlesavedInstanceState){wxShare=newWXShare(this);wxShare.setListener(newOnResponseListener(){@OverridepublicvoidonSuccess(){//分享成功}@OverridepublicvoidonCancel(){//分享取消}@OverridepublicvoidonFail(Stringmessage){//分享失败}});}@OverrideprotectedvoidonStart(){super.onStart();wxShare.register();}@OverrideprotectedvoidonDestroy(){wxShare.unregister();super.onDestroy();}

启动分享

wxShare.share("这是要分享的文字");

到这里微信分享就完成啦!

另外,在微信官方例程中,有个定时刷新应用注册信息的receiver

AndroidManifest.xml中添加:

<receiverandroid:name=".AppRegister"android:permission="com.tencent.mm.plugin.permission.SEND"><intent-filter><actionandroid:name="com.tencent.mm.plugin.openapi.Intent.ACTION_REFRESH_WXAPP"/></intent-filter></receiver>

代码:

publicclassAppRegisterextendsBroadcastReceiver{@OverridepublicvoidonReceive(Contextcontext,Intentintent){finalIWXAPIapi=WXAPIFactory.createWXAPI(context,null);//将该app注册到微信api.registerApp(WXShare.APP_ID);}}

读到这里,这篇“Android应用中如何接入微信分享功能”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注恰卡编程网行业资讯频道。

发布于 2022-04-11 21:17:30
收藏
分享
海报
0 条评论
20
上一篇:java线程中start和run的区别是什么 下一篇:Android中如何利用shape呈现出特殊效果
目录

    推荐阅读

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码