`

android-----------新浪微博

阅读更多
新浪微博:
包含功能:
1,新浪微博的登录
2,获取新浪用户的头像、昵称、性别
3,分享图片、文字到新浪微博

工程结构图:
[img]

[/img]

主类:
package com.amaker.sina;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

import org.json.JSONObject;

import com.weibo.net.AccessToken;
import com.weibo.net.AsyncWeiboRunner;
import com.weibo.net.DialogError;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;
import com.weibo.net.AsyncWeiboRunner.RequestListener;
import com.weibo.util.Authorize;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class SinaLoginActivity extends Activity implements RequestListener {
	public static final String SAVE_PIC_PATH = 
		Environment.getExternalStorageDirectory() + "/meilijie/imgs/";
	private HashMap<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
	private Button btn_login;
	private Button btn_save;
	private Button btn_share;
	private ImageView img_sina;
	private TextView txt_sina;
	private TextView txt_sex;
	private String uid;
	private String pic_url = "http://img.imeilijie.com/type/bag/tid/235114.jpg";


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
		//登陆新浪微博
		btn_login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				LoginSina();
				
			}
		});
		//保存一张图片到SD卡
		btn_save.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(SinaLoginActivity.this,SavePictureActivity.class);
				startActivity(intent);
			}
		});
		//分享图片到新浪微博
		btn_share.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				ShareToSina();
				
			}
		});

	}

	// 初始化控件
	public void init() {
		btn_login = (Button) findViewById(R.id.btn_login);
		btn_save = (Button) findViewById(R.id.btn_save);
		btn_share = (Button) findViewById(R.id.btn_share);
		img_sina = (ImageView) findViewById(R.id.img_sina);
		txt_sina = (TextView) findViewById(R.id.txt_sina);
		txt_sex = (TextView) findViewById(R.id.txt_sex);
	}

	public void LoginSina() {
		// Oauth2.0
		// 隐式授权认证方式
		// 获取微博实体类,传入appKey,appSecert,callback_url
		Weibo weibo = Weibo.getInstance();
		weibo.setupConsumerConfig(Authorize.CONSUMER_KEY,
				Authorize.CONSUMER_SECRET);

		// 此处回调页内容应该替换为与appKey对应的应用回调页
		weibo.setRedirectUrl("http://www.meilijie.com");
		// 对应的应用回调页可在开发者登陆新浪微博开发平台之后,
		// 进入我的应用--应用详情--应用信息--高级信息--授权设置--应用回调页进行设置和查看,
		// 应用回调页不可为空

		// 启动认证
		weibo.authorize(SinaLoginActivity.this, new AuthDialogListener());
	}

	// 用于新浪登录
	class AuthDialogListener implements WeiboDialogListener {
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			AccessToken accessToken = new AccessToken(token,
					Authorize.CONSUMER_SECRET);
			accessToken.setExpiresIn(expires_in);
			Weibo.getInstance().setAccessToken(accessToken);
			uid = values.getString("uid");
			
			try {
				getCounts(Weibo.getInstance());
			} catch (Exception e) {
				e.printStackTrace();
			}
			/*
			 * Intent intent = new Intent(MainActivity.this,SinaActivity.class);
			 * intent.putExtra("uid", uid + ""); startActivity(intent);
			 */
		}

		public void onError(DialogError e) {
			Toast.makeText(getApplicationContext(),
					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		public void onCancel() {
			Toast.makeText(getApplicationContext(), "Auth cancel",
					Toast.LENGTH_LONG).show();
		}

		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(),
					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}
	}

	// 新浪登录 获取用户资料
	public String getCounts(Weibo weibo) throws Exception {
		String url = Weibo.SERVER + "users/show.json";
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", Weibo.getAppKey());
		bundle.add("uid", uid);

		String rlt = weibo.request(this, url, bundle, "GET", weibo
				.getAccessToken());

		JSONObject jsonObject = new JSONObject(rlt);
		String name = jsonObject.getString("screen_name");
		String pic = jsonObject.getString("profile_image_url");
		String gender = jsonObject.getString("gender");
		String sex;
		if (gender.equalsIgnoreCase("m")) {
			sex = "男";
		} else if (gender.equalsIgnoreCase("f")) {
			sex = "女";
		} else {
			sex = "未知";
		}
		Bitmap bitmap = Authorize.returnBitMap(pic);
		img_sina.setImageBitmap(bitmap);
		txt_sina.setText("用户名:" + name);
		txt_sex.setText("    性别:" + sex);
		return rlt;
	}
	//新浪分享
	public void ShareToSina(){
			File file = Environment.getExternalStorageDirectory();
            String sdPath = file.getAbsolutePath();
            // 请保证SD卡根目录下有这张图片文件
            String picPath = sdPath + "/meilijie/imgs/" + "test.jpg";
            Log.i("test", "picPath:" + picPath);
            File picFile = new File(picPath);
            if (!picFile.exists()) {
                Toast.makeText(SinaLoginActivity.this, "图片" + picPath + "不存在!", 
                		Toast.LENGTH_SHORT).show();
                picPath = null;
            }
			try {
				String mContent = "测试图片新浪微博分享===李彩娜" +pic_url;
				Weibo weibo = Weibo.getInstance();
				
				upload(weibo, Weibo.getAppKey(), picPath, mContent, "", "");
			} catch (WeiboException e) {
				e.printStackTrace();
			}
		
	}
	//新浪分享
    private String upload(Weibo weibo, String source, String file, String status,
    		String lon, String lat) throws WeiboException {
        String url = Weibo.SERVER + "statuses/upload.json";
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", source);
        //要上传的图片,仅支持JPEG、GIF、PNG格式,图片大小小于5M。
        bundle.add("pic", file);
        //要发布的微博文本内容,必须做URLencode,内容不超过140个汉字。
        bundle.add("status", status);
        if (!TextUtils.isEmpty(lon)) {
            bundle.add("lon", lon);
        }
        if (!TextUtils.isEmpty(lat)) {
            bundle.add("lat", lat);
        }
        String rlt = "";
        AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
        weiboRunner.request(this, url, bundle, Utility.HTTPMETHOD_POST, this);

        return rlt;
    }
	
	
	@Override
	public void onComplete(String response) {
	}

	@Override
	public void onError(WeiboException e) {
	}

	@Override
	public void onIOException(IOException e) {
	}
	

}
  • 大小: 41.5 KB
分享到:
评论
2 楼 donala_zq 2013-11-30  
显示:[2013-11-30 11:50:36 - Android SDK] Warning when loading the SDK:

Warning: Ignoring sample 'ApiDemos': does not contain source.properties.
Warning: Ignoring sample 'BluetoothChat': does not contain source.properties.
Warning: Ignoring sample 'ContactManager': does not contain source.properties.
Warning: Ignoring sample 'CubeLiveWallpaper': does not contain source.properties.
Warning: Ignoring sample 'GestureBuilder': does not contain source.properties.
Warning: Ignoring sample 'Home': does not contain source.properties.
Warning: Ignoring sample 'JetBoy': does not contain source.properties.
Warning: Ignoring sample 'LunarLander': does not contain source.properties.
Warning: Ignoring sample 'MultiResolution': does not contain source.properties.
Warning: Ignoring sample 'NotePad': does not contain source.properties.
Warning: Ignoring sample 'SearchableDictionary': does not contain source.properties.
Warning: Ignoring sample 'SkeletonApp': does not contain source.properties.
Warning: Ignoring sample 'Snake': does not contain source.properties.
Warning: Ignoring sample 'SoftKeyboard': does not contain source.properties.
Warning: Ignoring sample 'Wiktionary': does not contain source.properties.
Warning: Ignoring sample 'WiktionarySimple': does not contain source.properties.
[2013-11-30 11:51:14 - Dex Loader] Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.
[2013-11-30 11:51:14 - SinaLoginTest] Conversion to Dalvik format failed: Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.
1 楼 donala_zq 2013-11-30  
哥,运行不了啊

相关推荐

Global site tag (gtag.js) - Google Analytics