欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-10-29 16:35:45
最近项目中要接入微信分享,记录下接入流程 注册应用信息并下载必要工具 在注册应用信息 下载 签名生成工具获取待接入应用的签名 应用信息填入签名...

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

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

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

@override
protected 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) {
      // 分享失败
    }
  });
}

@override
protected void onstart() {
  super.onstart();
  wxshare.register();
}

@override
protected 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);
  }
}

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