Android 微信SDK开发 - Demo

今天第一次使用微信的SDK来写个盆友圈分享的Demo,记录下学习笔记和遇到的问题。

1.先去微信开发者中心申请一个APPID,需要提交一些应用的信息,然后就是等待审核了。

2.创建一个Demo工程,记得导入从官网下载的libammsdk.jar. 然后就可以开始写代码咯。

Demo使用的布局文件 activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/reg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="将app注册到微信" />

    <Button
        android:id="@+id/share"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="分享测试信息到微信朋友圈" />

    <Button
        android:id="@+id/check"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="检查是否支持发送到朋友圈" />

</LinearLayout>

Demo主Activity WXEntryActivity.java

package com.example.wxapi;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.example.app.ConfigValues;
import com.example.wxdemo.R;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXTextObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
	private Button reg, share, check;
	private IWXAPI wxApi = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 初始化微信接口API
		wxApi = WXAPIFactory.createWXAPI(this, ConfigValues.APPID, true);
		wxApi.registerApp(ConfigValues.APPID);
		// 微信的回调
		wxApi.handleIntent(getIntent(), this);
		initView();
	}

	/**
	 * 初始化控件对象和监听器
	 */
	private void initView() {
		reg = (Button) findViewById(R.id.reg);
		share = (Button) findViewById(R.id.share);
		check = (Button) findViewById(R.id.check);

		reg.setOnClickListener(new ClickListener());
		share.setOnClickListener(new ClickListener());
		check.setOnClickListener(new ClickListener());
	}

	/**
	 * 发送文本到微信
	 */
	private void shareTxtToWx() {
		String text = "--->测试微信开发SDK分享功能<---";

		// 初始化一个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();
		// transaction字段用于唯一标识一个请求
		req.transaction = buildTransaction("text");
		// 请求消息内容
		req.message = msg;

		// 分享到朋友圈还是会话当中
		req.scene = SendMessageToWX.Req.WXSceneTimeline;
		// req.scene = WXSceneTimeline 代表分享内容到朋友圈
		// req.scene = WXSceneSession 代表分享内容到会话当中

		// 调用api接口发送数据到微信
		wxApi.sendReq(req);
	}

	/**
	 * 监听
	 */
	class ClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.reg:
				// 直接注册当前应用到微信
				wxApi.registerApp(ConfigValues.APPID);
				break;
			case R.id.share:
				// 分享测试文本到微信朋友圈
				shareTxtToWx();
				break;
			case R.id.check:
				// getWXAppSupportAPI返回的数值为0x21020001及以上支持发送朋友圈
				Toast.makeText(WXEntryActivity.this,
						"No:" + wxApi.getWXAppSupportAPI(), Toast.LENGTH_LONG)
						.show();
				break;
			}
		}
	}// class

	/**
	 * 格式化一下类型格式
	 * @param type
	 * @return
	 */
	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	/**
	 * 微信发送请求到第三方应用时,会回调到该方法
	 */
	@Override
	public void onReq(BaseReq arg0) {
		// TODO Auto-generated method stub

	}

	/**
	 * 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
	 */
	@Override
	public void onResp(BaseResp resp) {
		// TODO Auto-generated method stub
		String result = "";
		switch (resp.errCode) {
		case BaseResp.ErrCode.ERR_OK: // 分享成功
			result = "分享成功";
			break;
		case BaseResp.ErrCode.ERR_USER_CANCEL:// 取消分享
			result = "取消分享";
			break;
		case BaseResp.ErrCode.ERR_AUTH_DENIED:// // 分享失败
			result = "分享失败";
			break;
		default:
			result = "未知状态";
			break;
		}
		Toast.makeText(this, result, Toast.LENGTH_LONG).show();
	}

}


3.如果想在APP中使用微信的回调,必须在工程当中创建一个以 .wxapi ] 结尾的包,比如 com.example.wxapi,在包中还必须有一个类名为 WXEntryActivity的类文件,并且这个类要实现 IWXAPIEventHandler接口。

4.还要注意在AndroidManifest.xml里面注册WXEntryActivity.并且必须配置 [ android:exported="true" ].

<span style="white-space:pre">	</span><activity
            android:name="com.example.wxapi.WXEntryActivity"
            <span style="color:#ff0000;">android:exported="true"</span> >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

6.假如测试分享不能成功的话,或许是申请APPID时填写的应用签名的原因,可以去官方下载签名生成工具,从新获取一下应用签名,然后修改提交就OK了。



第一次在CSDN写博客,留作学习笔记吧,以后跟着大神们好好学习。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
List of Sample Apps The list below provides a summary of the sample applications that are available with the Android SDK. Using the links on this page, you can view the source files of the sample applications in your browser. You can also download the source of these samples into your SDK, then modify and reuse it as you need. For more information, see Getting the Samples. API Demos A variety of small applications that demonstrate an extensive collection of framework topics. Backup and Restore A simple example that illustrates a few different ways for an application to implement support for the Android data backup and restore mechanism. Bluetooth Chat An application for two-way text messaging over Bluetooth. BusinessCard An application that demonstrates how to launch the built-in contact picker from within an activity. This sample also uses reflection to ensure that the correct version of the contacts API is used, depending on which API level the application is running under. Contact Manager An application that demonstrates how to query the system contacts provider using the ContactsContract API, as well as insert contacts into a specific account. Home A home screen replacement application. JetBoy A game that demonstrates the SONiVOX JET interactive music technology, with JetPlayer. Live Wallpaper An application that demonstrates how to create a live wallpaper and bundle it in an application that users can install on their devices. Lunar Lander A classic Lunar Lander game. Multiple Resolutions A sample application that shows how to use resource directory qualifiers to provide different resources for different screen configurations. Note Pad An application for saving notes. Similar (but not identical) to the Notepad tutorial. SampleSyncAdapter Demonstrates how an application can communicate with a cloud-based service and synchronize its data with data stored locally in a content provider. The sample uses two related parts of the Android framework — the account manager and the synchronization manager (through a sync adapter). Searchable Dictionary A sample application that demonstrates Android's search framework, including how to provide search suggestions for Quick Search Box. Snake An implementation of the classic game "Snake." Soft Keyboard An example of writing an input method for a software keyboard. Spinner A simple application that serves as an application-under-test for the SpinnerTest sample application. SpinnerTest An example test application that contains test cases run against the Spinner sample application. To learn more about the application and how to run it, please read the Activity Testing tutorial. TicTacToeLib An example of an Android library project that provides a game-play Activity to any dependent application project. For an example of how an application can use the code and resources in an Android library project, see the TicTacToeMain sample application. TicTacToeMain An example of an Android application that makes use of code and resources provided in an Android library project. Specifically, this application uses code and resources provided in the TicTacToeLib library project. Wiktionary An example of creating interactive widgets for display on the Android home screen. Wiktionary (Simplified) A simple Android home screen widgets example.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值