`

android 之 新浪微博

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

工程结构图:
[img]

[/img]

主类:

Java代码 
1.package com.amaker.sina;  
2. 
3.import java.io.ByteArrayInputStream;  
4.import java.io.ByteArrayOutputStream;  
5.import java.io.File;  
6.import java.io.FileNotFoundException;  
7.import java.io.FileOutputStream;  
8.import java.io.IOException;  
9.import java.io.InputStream;  
10.import java.lang.ref.SoftReference;  
11.import java.net.MalformedURLException;  
12.import java.net.URL;  
13.import java.net.URLConnection;  
14.import java.util.HashMap;  
15. 
16.import org.json.JSONObject;  
17. 
18.import com.weibo.net.AccessToken;  
19.import com.weibo.net.AsyncWeiboRunner;  
20.import com.weibo.net.DialogError;  
21.import com.weibo.net.Utility;  
22.import com.weibo.net.Weibo;  
23.import com.weibo.net.WeiboDialogListener;  
24.import com.weibo.net.WeiboException;  
25.import com.weibo.net.WeiboParameters;  
26.import com.weibo.net.AsyncWeiboRunner.RequestListener;  
27.import com.weibo.util.Authorize;  
28.import android.app.Activity;  
29.import android.content.Intent;  
30.import android.graphics.Bitmap;  
31.import android.graphics.BitmapFactory;  
32.import android.graphics.Bitmap.CompressFormat;  
33.import android.graphics.drawable.BitmapDrawable;  
34.import android.graphics.drawable.Drawable;  
35.import android.os.Bundle;  
36.import android.os.Environment;  
37.import android.os.Handler;  
38.import android.os.Message;  
39.import android.text.TextUtils;  
40.import android.util.Log;  
41.import android.view.View;  
42.import android.view.View.OnClickListener;  
43.import android.widget.Button;  
44.import android.widget.ImageView;  
45.import android.widget.TextView;  
46.import android.widget.Toast;  
47. 
48.public class SinaLoginActivity extends Activity implements RequestListener {  
49.    public static final String SAVE_PIC_PATH =   
50.        Environment.getExternalStorageDirectory() + "/meilijie/imgs/";  
51.    private HashMap<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();  
52.    private Button btn_login;  
53.    private Button btn_save;  
54.    private Button btn_share;  
55.    private ImageView img_sina;  
56.    private TextView txt_sina;  
57.    private TextView txt_sex;  
58.    private String uid;  
59.    private String pic_url = "http://img.imeilijie.com/type/bag/tid/235114.jpg";  
60. 
61. 
62.    @Override 
63.    public void onCreate(Bundle savedInstanceState) {  
64.        super.onCreate(savedInstanceState);  
65.        setContentView(R.layout.main);  
66.        init();  
67.        //登陆新浪微博  
68.        btn_login.setOnClickListener(new OnClickListener() {  
69.            @Override 
70.            public void onClick(View v) {  
71.                  
72.                LoginSina();  
73.                  
74.            }  
75.        });  
76.        //保存一张图片到SD卡  
77.        btn_save.setOnClickListener(new OnClickListener() {  
78.            @Override 
79.            public void onClick(View v) {  
80.                  
81.                Intent intent = new Intent(SinaLoginActivity.this,SavePictureActivity.class);  
82.                startActivity(intent);  
83.            }  
84.        });  
85.        //分享图片到新浪微博  
86.        btn_share.setOnClickListener(new OnClickListener() {  
87.            @Override 
88.            public void onClick(View v) {  
89.                  
90.                ShareToSina();  
91.                  
92.            }  
93.        });  
94. 
95.    }  
96. 
97.    // 初始化控件  
98.    public void init() {  
99.        btn_login = (Button) findViewById(R.id.btn_login);  
100.        btn_save = (Button) findViewById(R.id.btn_save);  
101.        btn_share = (Button) findViewById(R.id.btn_share);  
102.        img_sina = (ImageView) findViewById(R.id.img_sina);  
103.        txt_sina = (TextView) findViewById(R.id.txt_sina);  
104.        txt_sex = (TextView) findViewById(R.id.txt_sex);  
105.    }  
106. 
107.    public void LoginSina() {  
108.        // Oauth2.0  
109.        // 隐式授权认证方式  
110.        // 获取微博实体类,传入appKey,appSecert,callback_url  
111.        Weibo weibo = Weibo.getInstance();  
112.        weibo.setupConsumerConfig(Authorize.CONSUMER_KEY,  
113.                Authorize.CONSUMER_SECRET);  
114. 
115.        // 此处回调页内容应该替换为与appKey对应的应用回调页  
116.        weibo.setRedirectUrl("http://www.meilijie.com");  
117.        // 对应的应用回调页可在开发者登陆新浪微博开发平台之后,  
118.        // 进入我的应用--应用详情--应用信息--高级信息--授权设置--应用回调页进行设置和查看,  
119.        // 应用回调页不可为空  
120. 
121.        // 启动认证  
122.        weibo.authorize(SinaLoginActivity.this, new AuthDialogListener());  
123.    }  
124. 
125.    // 用于新浪登录  
126.    class AuthDialogListener implements WeiboDialogListener {  
127.        public void onComplete(Bundle values) {  
128.            String token = values.getString("access_token");  
129.            String expires_in = values.getString("expires_in");  
130.            AccessToken accessToken = new AccessToken(token,  
131.                    Authorize.CONSUMER_SECRET);  
132.            accessToken.setExpiresIn(expires_in);  
133.            Weibo.getInstance().setAccessToken(accessToken);  
134.            uid = values.getString("uid");  
135.              
136.            try {  
137.                getCounts(Weibo.getInstance());  
138.            } catch (Exception e) {  
139.                e.printStackTrace();  
140.            }  
141.            /* 
142.             * Intent intent = new Intent(MainActivity.this,SinaActivity.class); 
143.             * intent.putExtra("uid", uid + ""); startActivity(intent); 
144.             */ 
145.        }  
146. 
147.        public void onError(DialogError e) {  
148.            Toast.makeText(getApplicationContext(),  
149.                    "Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();  
150.        }  
151. 
152.        public void onCancel() {  
153.            Toast.makeText(getApplicationContext(), "Auth cancel",  
154.                    Toast.LENGTH_LONG).show();  
155.        }  
156. 
157.        public void onWeiboException(WeiboException e) {  
158.            Toast.makeText(getApplicationContext(),  
159.                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)  
160.                    .show();  
161.        }  
162.    }  
163. 
164.    // 新浪登录 获取用户资料  
165.    public String getCounts(Weibo weibo) throws Exception {  
166.        String url = Weibo.SERVER + "users/show.json";  
167.        WeiboParameters bundle = new WeiboParameters();  
168.        bundle.add("source", Weibo.getAppKey());  
169.        bundle.add("uid", uid);  
170. 
171.        String rlt = weibo.request(this, url, bundle, "GET", weibo  
172.                .getAccessToken());  
173. 
174.        JSONObject jsonObject = new JSONObject(rlt);  
175.        String name = jsonObject.getString("screen_name");  
176.        String pic = jsonObject.getString("profile_image_url");  
177.        String gender = jsonObject.getString("gender");  
178.        String sex;  
179.        if (gender.equalsIgnoreCase("m")) {  
180.            sex = "男";  
181.        } else if (gender.equalsIgnoreCase("f")) {  
182.            sex = "女";  
183.        } else {  
184.            sex = "未知";  
185.        }  
186.        Bitmap bitmap = Authorize.returnBitMap(pic);  
187.        img_sina.setImageBitmap(bitmap);  
188.        txt_sina.setText("用户名:" + name);  
189.        txt_sex.setText("    性别:" + sex);  
190.        return rlt;  
191.    }  
192.    //新浪分享  
193.    public void ShareToSina(){  
194.            File file = Environment.getExternalStorageDirectory();  
195.            String sdPath = file.getAbsolutePath();  
196.            // 请保证SD卡根目录下有这张图片文件  
197.            String picPath = sdPath + "/meilijie/imgs/" + "test.jpg";  
198.            Log.i("test", "picPath:" + picPath);  
199.            File picFile = new File(picPath);  
200.            if (!picFile.exists()) {  
201.                Toast.makeText(SinaLoginActivity.this, "图片" + picPath + "不存在!",   
202.                        Toast.LENGTH_SHORT).show();  
203.                picPath = null;  
204.            }  
205.            try {  
206.                String mContent = "测试图片新浪微博分享===李彩娜" +pic_url;  
207.                Weibo weibo = Weibo.getInstance();  
208.                  
209.                upload(weibo, Weibo.getAppKey(), picPath, mContent, "", "");  
210.            } catch (WeiboException e) {  
211.                e.printStackTrace();  
212.            }  
213.          
214.    }  
215.    //新浪分享  
216.    private String upload(Weibo weibo, String source, String file, String status,  
217.            String lon, String lat) throws WeiboException {  
218.        String url = Weibo.SERVER + "statuses/upload.json";  
219.        WeiboParameters bundle = new WeiboParameters();  
220.        bundle.add("source", source);  
221.        //要上传的图片,仅支持JPEG、GIF、PNG格式,图片大小小于5M。  
222.        bundle.add("pic", file);  
223.        //要发布的微博文本内容,必须做URLencode,内容不超过140个汉字。  
224.        bundle.add("status", status);  
225.        if (!TextUtils.isEmpty(lon)) {  
226.            bundle.add("lon", lon);  
227.        }  
228.        if (!TextUtils.isEmpty(lat)) {  
229.            bundle.add("lat", lat);  
230.        }  
231.        String rlt = "";  
232.        AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);  
233.        weiboRunner.request(this, url, bundle, Utility.HTTPMETHOD_POST, this);  
234. 
235.        return rlt;  
236.    }  
237.      
238.      
239.    @Override 
240.    public void onComplete(String response) {  
241.    }  
242. 
243.    @Override 
244.    public void onError(WeiboException e) {  
245.    }  
246. 
247.    @Override 
248.    public void onIOException(IOException e) {  
249.    }  
250.      
251. 
252.} 


SinaLoginTest.zip (757.9 KB)
http://dl.iteye.com/topics/download/c6b592be-ea70-334c-ab55-8517dc7e2686
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics