Android应用接入微信分享的实例代码

Android应用接入微信分享的实例代码,第1张

概述最近项目中要接入微信分享,记录下接入流程注册应用信息并下载必要工具在微信开放平台注册应用信息

最近项目中要接入微信分享,记录下接入流程

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

在微信开放平台注册应用信息 下载 签名生成工具获取待接入应用的签名 应用信息填入签名

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

接入

在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-permission androID:name="androID.permission.INTERNET" /><uses-permission androID:name="androID.permission.MODIFY_AUdio_SETTINGS"/><uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE"/><!-- for mta statistics --><uses-permission androID:name="androID.permission.ACCESS_WIFI_STATE"/><uses-permission androID:name="androID.permission.READ_PHONE_STATE"/><uses-permission androID:name="androID.permission.ACCESS_NETWORK_STATE"/><activity  androID:name=".WXEntryActivity"  androID:exported="true"  androID:screenorIEntation="portrait"  androID:theme="@style/Apptheme.Fullscreen.Translucent"/>

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

主题:

<style name="Apptheme.Fullscreen" parent="theme.AppCompat.NoActionbar">  <item name="androID:windowNoTitle">true</item>  <item name="androID:windowFullscreen">true</item>  <item name="androID:windowTranslucentNavigation" tools:targetAPI="kitkat">true</item></style><style name="Apptheme.Fullscreen.Translucent">  <item name="androID:windowBackground">@androID:color/transparent</item>  <item name="androID:windowIsTranslucent">true</item>  <item name="androID:windowAnimationStyle">@androID:style/Animation.Translucent</item></style>

Activity

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

public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {    private IWXAPI API;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      Logger.i("WXEntryActivity");      WXShare share = new WXShare(this);      API = share  //        .register()          .getAPI();      //注意:      //第三方开发者如果使用透明界面来实现WXEntryActivity,需要判断handleIntent的返回值,如果返回值为false,则说明入参不合法未被SDK处理,应finish当前透明界面,避免外部通过传递非法参数的Intent导致停留在透明界面,引起用户的疑惑      try {        if (!API.handleIntent(getIntent(),this)) {          finish();        }      } catch (Exception e) {        e.printstacktrace();      }    }    @OverrIDe    protected voID onNewIntent(Intent intent) {      super.onNewIntent(intent);      Logger.i("onNewIntent");      setIntent(intent);      if (!API.handleIntent(intent,this)) {        finish();      }    }    @OverrIDe    public voID onReq(BaseReq baseReq) {    }    @OverrIDe    public voID onResp(BaseResp baseResp) {      Intent intent = new Intent(WXShare.ACTION_SHARE_RESPONSE);      intent.putExtra(WXShare.EXTRA_RESulT,new WXShare.Response(baseResp));      sendbroadcast(intent);      finish();    }  }

工具类

public class WXShare {    public static final String APP_ID = "wx0123456789";    public static final String ACTION_SHARE_RESPONSE = "action_wx_share_response";    public static final String EXTRA_RESulT = "result";    private final Context context;    private final IWXAPI API;    private OnResponseListener Listener;    private ResponseReceiver receiver;    public WXShare(Context context) {      API = WXAPIFactory.createWXAPI(context,APP_ID);      this.context = context;    }    public WXShare register() {      // 微信分享      API.registerapp(APP_ID);      receiver = new ResponseReceiver();      IntentFilter filter = new IntentFilter(ACTION_SHARE_RESPONSE);      context.registerReceiver(receiver,filter);      return this;    }    public voID unregister() {      try {        API.unregisterapp();        context.unregisterReceiver(receiver);      } catch (Exception e) {        e.printstacktrace();      }    }    public WXShare share(String text) {      WXTextObject textObj = new WXTextObject();      textObj.text = text;      WXMediaMessage msg = new WXMediaMessage();      msg.mediaObject = textObj;  //    msg.Title = "Will be ignored";      msg.description = text;      SendMessagetoWX.Req req = new SendMessagetoWX.Req();      req.transaction = buildTransaction("text");      req.message = msg;      req.scene = SendMessagetoWX.Req.WXScenesession;      boolean result = API.sendReq(req);      Logger.i("text shared: " + result);      return this;    }    public IWXAPI getAPI() {      return API;    }    public voID setListener(OnResponseListener Listener) {      this.Listener = Listener;    }    private String buildTransaction(final String type) {      return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();    }    private class ResponseReceiver extends broadcastReceiver {      @OverrIDe      public voID onReceive(Context context,Intent intent) {        Response response = intent.getParcelableExtra(EXTRA_RESulT);        Logger.d("type: " + response.getType());        Logger.d("errCode: " + response.errCode);        String result;        if (Listener != null) {          if (response.errCode == BaseResp.ErrCode.ERR_OK) {            Listener.onSuccess();          } else if (response.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {            Listener.onCancel();          } else {            switch (response.errCode) {              case BaseResp.ErrCode.ERR_AUTH_DENIED:                result = "发送被拒绝";                break;              case BaseResp.ErrCode.ERR_UNSUPPORT:                result = "不支持错误";                break;              default:                result = "发送返回";                break;            }            Listener.onFail(result);          }        }      }    }    public static class Response extends BaseResp implements Parcelable {      public int errCode;      public String errStr;      public String transaction;      public String openID;      private int type;      private boolean checkResult;      public Response(BaseResp baseResp) {        errCode = baseResp.errCode;        errStr = baseResp.errStr;        transaction = baseResp.transaction;        openID = baseResp.openID;        type = baseResp.getType();        checkResult = baseResp.checkArgs();      }      @OverrIDe      public int getType() {        return type;      }      @OverrIDe      public boolean checkArgs() {        return checkResult;      }      @OverrIDe      public int describeContents() {        return 0;      }      @OverrIDe      public voID writetoParcel(Parcel dest,int flags) {        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);      }      protected Response(Parcel in) {        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;      }      public static final Creator<Response> CREATOR = new Creator<Response>() {        @OverrIDe        public Response createFromParcel(Parcel source) {          return new Response(source);        }        @OverrIDe        public Response[] newArray(int size) {          return new Response[size];        }      };    }  }

接口

public interface OnResponseListener {  voID onSuccess();  voID onCancel();  voID onFail(String message);}

使用

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

@OverrIDeprotected voID onCreate(Bundle savedInstanceState) {  wxShare = new WXShare(this);  wxShare.setListener(new OnResponseListener() {    @OverrIDe    public voID onSuccess() {      // 分享成功    }    @OverrIDe    public voID onCancel() {      // 分享取消    }    @OverrIDe    public voID onFail(String message) {      // 分享失败    }  });}@OverrIDeprotected voID onStart() {  super.onStart();  wxShare.register();}@OverrIDeprotected voID onDestroy() {  wxShare.unregister();  super.onDestroy();}

启动分享

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

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

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

AndroIDManifest.xml中添加:

<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>

代码

public class AppRegister extends broadcastReceiver {  @OverrIDe  public voID onReceive(Context context,Intent intent) {    final IWXAPI API = WXAPIFactory.createWXAPI(context,null);    // 将该app注册到微信    API.registerapp(WXShare.APP_ID);  }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android应用接入微信分享的实例代码全部内容,希望文章能够帮你解决Android应用接入微信分享的实例代码所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1145687.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存