码迷,mamicode.com
首页 > 微信 > 详细

微信SDK开发学习

时间:2016-02-26 12:10:15      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:

public class MainActivity extends Activity {
// 应用程序的id,就是在网上开发平台创建应用的appid
public static final String APP_ID = "wx00e5fafe00473016";
// 微信api的访问变量
private IWXAPI iwxapi;
private CheckBox mshareFriends;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

iwxapi = WXAPIFactory.createWXAPI(getApplicationContext(), APP_ID);
// 将appid注册到微信中
iwxapi.registerApp(APP_ID);

mshareFriends = (CheckBox) findViewById(R.id.cb_shareFriends);
}

// 启动微信
public void launch_weixin(View v) {
if (iwxapi.openWXApp()) {
Toast.makeText(getApplicationContext(), "打开微信成功", 3).show();
} else {
Toast.makeText(getApplicationContext(), "打开微信失败", 3).show();
}
}

// 为请求生成一个唯一的表示
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis())
: type + System.currentTimeMillis();
}

// 向好友或者朋友圈发送文本
public void send_txt(View v) {
// 创建edittext控件,用于输入文本
final EditText editText = new EditText(getApplicationContext());
editText.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editText.setText("用程序分享的默认文本");

AlertDialog.Builder builder = new AlertDialog.Builder(this).setIcon(
R.drawable.ic_launcher).setTitle("共享文本");
// 将edittext与对话框绑定
builder.setView(editText);
builder.setMessage("请输入要分享的文本");
builder.setPositiveButton("分享", new OnClickListener() {

@Override
public void onClick(DialogInterface arg0, int arg1) {
String text = editText.getText().toString();
if (text == null || text.length() == 0) {
return;
}
// 1 创建一个用于封装待分享文本的WXTextObject对象
WXTextObject textObject = new WXTextObject();
textObject.text = text;
// 2创建WXMediaMessage对象,该对象用于android客户端向微信发送数据
WXMediaMessage mediaMessage = new WXMediaMessage();
mediaMessage.mediaObject = textObject;
mediaMessage.description = text;
// 3创建一个用于请求微信客户端的SendMessageToWX.Req对象
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.message = mediaMessage;
req.transaction = buildTransaction("text");
// 发送给朋友还是朋友圈
req.scene = mshareFriends.isChecked() ? req.WXSceneTimeline
: req.WXSceneSession;
// 4 发送给微信客户端
Toast.makeText(getApplicationContext(),
String.valueOf(iwxapi.sendReq(req)), Toast.LENGTH_SHORT)
.show();

}
}).setNegativeButton("取消", null);
AlertDialog dialog=builder.create();
dialog.show();

}
}

微信SDK开发学习

标签:

原文地址:http://www.cnblogs.com/wangfeng520/p/5219808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!