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-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);
  }
}

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

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。