Android 编程之第三方开发 MaoZhuaWeiBo微博开发演示样例-1「建议收藏」

Android 编程之第三方开发 MaoZhuaWeiBo微博开发演示样例-1

大家好,又见面了,我是全栈君。

在大学期间我做过非常多类似这种APP。这个是我们小组之前做的,我后期增加非常多新元素。完好了这个应用,由于为了加强

专业技术嘛。也是常常熬夜写些小东西,嘿嘿。只是还算不错。起码技术长进了不少嘛,还是非常欣慰的,今天给大家说说腾讯

微博第三方拓展client开发。说白了就是调用第三方接口的开放平台进行二次开发,跟微信有些类似吧,好了,不扯了。立即

进入正题吧

开发前准备:

① 腾讯QQ号(相信大家都有)     ②腾讯微博 App key (申请地址:http://dev.t.qq.com/)  ③API地址:http://wiki.open.t.qq.com/index.php/API%E6%96%87%E6%A1%A3

可能有些人会问。为什么不用新浪微博开发呢? 我就这么说吧,新浪的审核超慢。。

。等审核下来,预计咱们早就写完了


然后就開始着手我们的微博撰写了,把基本的架子搭好,我个人感觉先功能在UI比較好。由于UI后写的话,能够相对降低工作量,由于主要核心还是在功能,而UI是给用户不同的视觉体验吧


创建好Project之后,先给咱们的清单文件xml载入权限代码:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

接下来就是应用程序启动Activity,LoginActivity

package com.neweriweibo.activity;
/**
 * 登录
 * @author Engineer-Jsp
 * @date 2014.10.29*/
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.neweriweibo.MainActivity;
import com.neweriweibo.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class LoginActivity extends Activity {

	private int[] mimageIds;
	private String[] titles;
	private ArrayList<ImageView> mimage;
	private ViewPager mvp;
	private MyAdapter madapter;
	private TextView mtitle;
	private ArrayList<View> mdots;
	private int oldPosition = 0; // 记录上一次点的位置\
	private int currentItem; // 当前页面

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.fristpager);

		
		getActionBar().hide();
		// 图片
		mimageIds = new int[] { R.drawable.aa, R.drawable.bb, R.drawable.cc,
				R.drawable.dd, };
		// 图标标题
		titles = new String[] { "随时随地分享你的信息", "不要一个人说话。", "不要默默的去快乐",
				"让世界聆听你的心声" };

		mimage = new ArrayList<ImageView>();
		for (int i = 0; i < mimageIds.length; i++) {
			ImageView imageview = new ImageView(this);
			imageview.setBackgroundResource(mimageIds[i]);

			mimage.add(imageview);
		}

		mdots = new ArrayList<View>();

		mdots.add(findViewById(R.id.dot_0));
		mdots.add(findViewById(R.id.dot_1));
		mdots.add(findViewById(R.id.dot_2));
		mdots.add(findViewById(R.id.dot_3));

		mtitle = (TextView) findViewById(R.id.title);

		mtitle.setText(titles[0]);

		mvp = (ViewPager) findViewById(R.id.vp);

		madapter = new MyAdapter();
		mvp.setAdapter(madapter);

		mvp.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {

				mtitle.setText(titles[position]);

				mdots.get(oldPosition).setBackgroundResource(
						R.drawable.dot_normarl);
				mdots.get(position).setBackgroundResource(
						R.drawable.dot_focused);
				oldPosition = position;
				// 记录下当前界面的位置:(线程的使用)
				currentItem = position;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
	}

	class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
		
			return mimage.size();
		}

		/* 推断是否是同一张图片 */
		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {

			return arg0 == arg1;
		}

		@Override
		public Object instantiateItem(ViewGroup view, int position) {

			view.addView(mimage.get(position));
			return mimage.get(position);

		}

		@Override
		public void destroyItem(ViewGroup view, int position, Object object) {

			// super.destroyItem(container, position, object);
			view.removeView(mimage.get(position));
			// view.removeViewAt(position);
		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		// 线程池
		ScheduledExecutorService sched = Executors
				.newSingleThreadScheduledExecutor();
		sched.scheduleWithFixedDelay(new ViewPagerTask(), 3, 3,
				TimeUnit.SECONDS);
	}

	/* 任务切换图片 */
	private class ViewPagerTask implements Runnable {

		@Override
		public void run() {

			currentItem = (currentItem + 1) % mimageIds.length;
			// 更新界面
			handler.obtainMessage().sendToTarget();
		}

	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			mvp.setCurrentItem(currentItem);
		};
	};

	@Override
	protected void onStop() {

		super.onStop();
	}
	
	/*
	 * 进入微博主页或者验证授权
	 */
	 public void login(View v){
		 //首选项抓凭证
		 String access_token = PreferenceManager.getDefaultSharedPreferences(this).getString("access_token", null) ;
		 
		 if(null!=access_token){
			 // 不为空intent至主页
			 startActivity(new Intent(LoginActivity.this,MainActivity.class));
		 }else{
			 // 空至授权界面
			 startActivity(new Intent(LoginActivity.this,OAuthActivity.class));
		 }
	 }

	
	

}

由于我的IU写得太渣。。

布局文件就。

。。。有兴趣的话还是看源代码吧,讲完这个APP之后将会贴上来

以下说说凭证抓取的各自结果截图,代码:

抓取成功:

package com.neweriweibo; /** * 主活动 * @author Engineer-Jsp * @date 2014.10.28 * */ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import com.neweriweibo.activity.SendMessageActivity; import com.neweriweibo.adapter.MessageAdapter; import com.neweriweibo.model.User; import com.neweriweibo.model.UserWeiBiInfo; import com.neweriweibo.service.UserService; import com.squareup.picasso.Picasso; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.SpinnerAdapter; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener,OnNavigationListener{ public static String [] data; private ShouYeFragment shouyeFragment ; private MessageFragment messageFragment ; private UserFragment userFragment ; private SeacherFragment seacherFragment ; private View mfristLayout ; private View mmessageLayout ; private View muserLayout ; private View msousuoLayout ; private ImageView shouyeImage ; private ImageView messageImage ; private ImageView userImage ; private ImageView sousuoImage ; private FragmentManager mfragmentManager ; private SpinnerAdapter spinnerAdapter; private List<String> dropData = null ; private static int itemPosition = 0 ; private String access_token; private String openid; private String openkey; private static ListView lvMessage; private static ArrayList<UserWeiBiInfo> userWeiBoData = null; private static MessageAdapter messageAdapter; //static 说明是静态的对象,能够直接用(类名.对象)来调用。

//Public与Private 是对象的訪问权限 //public(共同拥有) 说明不论什么类在不论什么地方都能调用它 //private(私有) 说明仅仅有在本类内被调用 public static User user ; private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().endsWith("messagett")){ new TimeLineAsyncTask(MainActivity.this).execute() ; messageAdapter.notifyDataSetChanged(); lvMessage.setAdapter(messageAdapter) ; }else{ user = intent.getParcelableExtra(UserService.NOW_WEATHER) ; Log.i("广播接收到的用户个人信息:", user.toString()) ; } } }; @Override protected void onStart() { super.onStart(); registerReceiver(receiver, new IntentFilter("messagett")); registerReceiver(receiver, new IntentFilter(UserService.UPDATA)); } @Override protected void onStop() { super.onStop(); unregisterReceiver(receiver) ; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initView() ; access_token = PreferenceManager.getDefaultSharedPreferences(this).getString("access_token", "access_token"); openid = PreferenceManager.getDefaultSharedPreferences(this).getString("openid", "openid"); openkey = PreferenceManager.getDefaultSharedPreferences(this).getString("openkey", "openkey"); Log.i("首选项保存的信息:","access_token :" + access_token+"\n"+ "openid :" + openid +"\n"+ "openkey :" + openkey ); new TimeLineAsyncTask(this).execute() ; ActionBar actionBar = getActionBar() ; actionBar.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.bg_btn_nor)); actionBar.setDisplayHomeAsUpEnabled(true) ; //设置actionBar的图片的可见性 dropData = new ArrayList<String>() ; dropData.add("我的微博") ; dropData.add("好友圈") ; dropData.add("周边微博") ; spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, dropData); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST) ; //设置actionBar的模式 actionBar.setListNavigationCallbacks(spinnerAdapter, this); mfragmentManager = getFragmentManager(); setTabSelection(0) ; //设置默认的Fragment选项 Intent intent = new Intent(this,UserService.class) ; startService(intent) ; } /** * 初始化控件 */ private void initView() { mfristLayout = findViewById(R.id.shouye_layout); mmessageLayout = findViewById(R.id.message_layout); muserLayout = findViewById(R.id.user_layout); msousuoLayout = findViewById(R.id.sousuo_layout); shouyeImage = (ImageView) findViewById(R.id.shouye_image); messageImage = (ImageView) findViewById(R.id.message_image); userImage = (ImageView) findViewById(R.id.user_image); sousuoImage = (ImageView) findViewById(R.id.sousuo_image); mfristLayout.setOnClickListener(this); mmessageLayout.setOnClickListener(this); muserLayout.setOnClickListener(this); msousuoLayout.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_sendmessage: //编写消息 Intent intent = new Intent(MainActivity.this,SendMessageActivity.class) ; startActivity(intent); break; default: break; } return super.onOptionsItemSelected(item); } private void setTabSelection(int index) { clearSelection() ; //清除所选中的状态 FragmentTransaction _transaction = mfragmentManager.beginTransaction() ; hideFragments(_transaction); //隐藏碎片 switch (index) { case 0: // 当点击了消息tab时,改变控件的图片和文字颜色 shouyeImage.setImageResource(R.drawable.shouye01); if (shouyeFragment == null) { shouyeFragment = new ShouYeFragment() ; _transaction.add(R.id.content, shouyeFragment); } else { _transaction.show(shouyeFragment); } break; case 1: // 当点击了联系人tab时,改变控件的图片和文字颜色 messageImage.setImageResource(R.drawable.xiaoxi01); if (messageFragment == null) { messageFragment = new MessageFragment(); _transaction.add(R.id.content, messageFragment); } else { _transaction.show(messageFragment); } break; case 2: // 当点击了动态tab时,改变控件的图片和文字颜色 userImage.setImageResource(R.drawable.yonghu01); if (userFragment == null) { userFragment = new UserFragment(); _transaction.add(R.id.content, userFragment); } else { _transaction.show(userFragment); } break; case 3: // 当点击了设置tab时,改变控件的图片和文字颜色 sousuoImage.setImageResource(R.drawable.chazhao01); if (seacherFragment == null) { seacherFragment = new SeacherFragment(); _transaction.add(R.id.content, seacherFragment); } else { _transaction.show(seacherFragment); } break ; default: break; } _transaction.commit(); } private void hideFragments(FragmentTransaction _transaction) { if (shouyeFragment != null) { _transaction.hide(shouyeFragment); } if (messageFragment != null) { _transaction.hide(messageFragment); } if (userFragment != null) { _transaction.hide(userFragment); } if (seacherFragment != null) { _transaction.hide(seacherFragment); } } /* * 用户清除点击进入界面所须要清除的全部状态 */ private void clearSelection() { shouyeImage.setImageResource(R.drawable.shouye) ; messageImage.setImageResource(R.drawable.xiaoxi) ; userImage.setImageResource(R.drawable.yonghu) ; sousuoImage.setImageResource(R.drawable.chazhao) ; } /* * 底部Fragment点击事件所相应页面的显示 * (non-Javadoc) * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { int Fragmentid = v.getId() ; switch (Fragmentid) { case R.id.shouye_layout: setTabSelection(0) ; break; case R.id.message_layout: setTabSelection(1) ; break; case R.id.user_layout: setTabSelection(2) ; break; case R.id.sousuo_layout: setTabSelection(3) ; break; default: break; } } /** * 异步载入微博消息 * @author Administrator * */ private class TimeLineAsyncTask extends AsyncTask<Void, Void, ArrayList<UserWeiBiInfo>> { Context context ; public TimeLineAsyncTask(Context pcontext) { context = pcontext ; userWeiBoData = new ArrayList<UserWeiBiInfo>(); } @Override protected ArrayList<UserWeiBiInfo> doInBackground(Void... params) { UserWeiBiInfo userWeiBo = null; String json = ""; String url = "http://open.t.qq.com/api/statuses/home_timeline"; StringBuffer buff = new StringBuffer(url) ; String path = buff.append("?").append("format=json&pageflag=0&pagetime=0&reqnum=5&lastid=0&type=3&contenttype=0x80") .append("&oauth_consumer_key=801506545").append("&access_token="+access_token).append("&openid="+openid) .append("&clientip=CLIENTIP").append("&oauth_version=2.a").append("&scope=all").toString() ; HttpGet get = new HttpGet(path); HttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { json = EntityUtils.toString(response.getEntity(), "utf-8"); JSONObject root = new JSONObject(json); JSONObject data = root.getJSONObject("data"); Log.d("微博消息列表:", data.toString()); JSONArray info = data.getJSONArray("info"); for (int i = 0; i < info.length(); i++) { userWeiBo = new UserWeiBiInfo(); JSONObject object = (JSONObject) info.get(i); String id = object.getString("id"); String name = object.getString("name"); String origtext = object.getString("origtext"); String headimg = object.getString("head")+"/40"; userWeiBo.setId(id); userWeiBo.setName(name); userWeiBo.setOrigtext(origtext); userWeiBo.setHeadimg(headimg); Log.i("微博好友近期动态:", userWeiBo.toString()); userWeiBoData.add(userWeiBo); } } } catch (Exception e) { e.printStackTrace() ; } return userWeiBoData; } @Override protected void onPostExecute(ArrayList<UserWeiBiInfo> result) { super.onPostExecute(result); messageAdapter = new MessageAdapter(context,result); messageAdapter.notifyDataSetChanged(); } } public static class ShouYeFragment extends Fragment{ private GridView gridview ; private SimpleAdapter adapter; private String[] text; private int[]icon={R.drawable.icon_1,R.drawable.icon_2,R.drawable.icon_3, R.drawable.icon_4,R.drawable.icon_5,R.drawable.icon_6}; private List<Map<String,Object>> list = new ArrayList<Map<String, Object>>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); text = getResources().getStringArray(R.array.array); for(int i=0;i<text.length;i++){ Map<String,Object> map = new HashMap<String, Object>(); map.put("img", icon[i]); map.put("name", text[i]); list.add(map); } adapter = new SimpleAdapter(getActivity(), list, R.layout.log, new String[]{"img","name"}, new int []{R.id.g_icon,R.id.g_text}); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_shouye, container, false) ; gridview = (GridView)view.findViewById(R.id.gridView); ImageView icon = (ImageView)view.findViewById(R.id.icon);//头像 TextView name = (TextView)view.findViewById(R.id.name);//昵称 TextView time = (TextView)view.findViewById(R.id.time);//时间// File file = new File(Environment.getExternalStorageDirectory()+"/"+"weiinfo") ; BufferedReader reader = null ; String line = null ; try { reader = new BufferedReader(new FileReader(file)) ; line = reader.readLine() ; } catch (Exception e) { e.printStackTrace(); } data = line.split("\\*") ; Picasso.with(getActivity().getApplicationContext()).load(data[5]).into(icon); name.setText(data[0]); time.setText("Time"); gridview.setAdapter(adapter); return view ; } } public static class MessageFragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_message, container, false) ; lvMessage = (ListView)view.findViewById(R.id.lv_message); messageAdapter = new MessageAdapter(getActivity(),userWeiBoData); messageAdapter.notifyDataSetChanged(); lvMessage.setAdapter(messageAdapter) ; return view ; } } public static class UserFragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.user, container, false) ; ImageView headimg2 = (ImageView)view.findViewById(R.id.head) ; //头像2 TextView nick2 = (TextView)view.findViewById(R.id.nick2) ; // 昵称2 TextView nearinfo = (TextView)view.findViewById(R.id.nearinfo) ; // 用户近期的一条原创微博 ImageView headimg = (ImageView)view.findViewById(R.id.headimg) ;//用户头像上 TextView tvName = (TextView)view.findViewById(R.id.text1_nick) ; //username称 TextView brith = (TextView)view.findViewById(R.id.text2_br) ; //用户生日 TextView tv_location = (TextView)view.findViewById(R.id.location) ; //用户地址 TextView usertitle = (TextView)view.findViewById(R.id.text3_info) ; //用户资料 TextView fabiao = (TextView)view.findViewById(R.id.fabiao) ; //微博数量 TextView shouting = (TextView)view.findViewById(R.id.shouting); //关注数 TextView tingzhong = (TextView)view.findViewById(R.id.tingzhong);// 被关注数 TextView sex = (TextView)view.findViewById(R.id.sex);// 性别 1-男。2-女,0-未填写 if(user!=null){ Picasso.with(getActivity().getApplicationContext()).load(user.getHeadimg()).into(headimg); tvName.setText(user.getNick()); brith.setText(user.getBirthyeaer()+"/"+user.getBirthmonth()+"/"+user.getBirthday()); tv_location.setText(user.getLoacation()); usertitle.setText(user.getInfo()); tingzhong.setText(user.getFansnum()); shouting.setText(user.getIdonum()); fabiao.setText(user.getTweetnum()); sex.setText(user.getSex()); Picasso.with(getActivity().getApplicationContext()).load(user.getHeadimg()).into(headimg2); nick2.setText(user.getNick()+"最新动态:\n\n"); nearinfo.setText(user.getNearinfo()); }else{ File file = new File(Environment.getExternalStorageDirectory()+"/"+"weiinfo") ; BufferedReader reader = null ; String line = null ; try { reader = new BufferedReader(new FileReader(file)) ; line = reader.readLine() ; } catch (Exception e) { e.printStackTrace(); } data = line.split("\\*") ; Log.d("没有获取到网络抓取数据,载入本地文件:", "数组长度:"+data.length); for(int i=0;i<data.length;i++){ Log.d("本地数据的排序:",i+":"+ data[i]); } tvName.setText(data[0]); //昵称 nick2.setText(data[0]); shouting.setText(data[1]); //关注数 tv_location.setText(data[2]);//位置 brith.setText(data[3]);//生日 usertitle.setText(data[4]);//自我介绍 Picasso.with(getActivity().getApplicationContext()).load(data[5]).into(headimg);//头像 Picasso.with(getActivity().getApplicationContext()).load(data[5]).into(headimg2); tingzhong.setText(data[6]);//粉丝数 fabiao.setText(data[7]);//微博数 sex.setText(data[8]);//性别 nearinfo.setText(data[9]);//近期动态 } return view ; } } public static class SeacherFragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_sousuo, container, false) ; return view ; } } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { MainActivity.itemPosition = itemPosition ; return true; }}

结果图,个人信息界面,网络抓取。解析,没有网络时。保存了最后一次动态的数据在本地:

Android 编程之第三方开发 MaoZhuaWeiBo微博开发演示样例-1「建议收藏」


数据都是来自腾讯server的。不是本地的。首页界面:

Android 编程之第三方开发 MaoZhuaWeiBo微博开发演示样例-1「建议收藏」


这个GridView我还没有做不论什么拓展。只是我前面说到的的天气预报和文件管理器能够嵌入进来,能够解决掉一半,有兴趣的能够继续写下去,还有附近功能,我有时间会把它写了,贴出来,供大家学习


凭证抓取失败的结果,跳转至授权界面。授权成功,信息保存至首选项:

package com.neweriweibo.activity; /** * 授权 * @author Engineer-Jsp * @date 2014.10.28 * */ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import com.neweriweibo.R; import com.neweriweibo.MainActivity; import com.neweriweibo.R.id; import com.neweriweibo.R.layout; import com.neweriweibo.utils.TencentAPI; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class OAuthActivity extends Activity { private static final String TAG = "float" ; private WebView webView; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_load); webView = (WebView) findViewById(R.id.webview); WebSettings webSetting = webView.getSettings() ; //获取设置对象 webSetting.setJavaScriptEnabled(true); //设置WebView 支持JavaScript webView.setWebViewClient(mClient); /** * BasicNameValuePair实现了NameValuePair接口 : * String getName(); * String getValue(); */ List<BasicNameValuePair> _list = new ArrayList<BasicNameValuePair>() ; _list.add(new BasicNameValuePair("client_id",TencentAPI.client_id)) ; _list.add(new BasicNameValuePair("redirect_uri",TencentAPI.redirectUri)) ; _list.add(new BasicNameValuePair("response_type",TencentAPI.response_type)) ; String param = URLEncodedUtils.format(_list, "utf-8") ; webView.loadUrl(TencentAPI.url + "?" +param) ; //载入授权登入界面 Log.d("授权地址:", TencentAPI.url+"?

"+param); } //:主要实现:获取access_token :access_token=789a7d5284d0c3e608f8e384c993d04b (授权码) private WebViewClient mClient = new WebViewClient(){ public void onPageStarted(WebView view, String url, android.graphics.Bitmap favicon) { Log.i("打印授权地址:", url) ; /* * http://www.newer.com/#access_token=789a7d5284d0c3e608f8e384c993d04b&expires_in=8035200&openid=0027BC08DB5B45D7461E9A0F16F527E7&openkey=60A1DF40C01EE30537AF7739504DFDB0&refresh_token=5c768f8850ae5af2193ce79f3f0a1351&state=&name=cfloat656805&nick=Cfloat * 完毕之后会在你该应用的网址上返回授权server重定向浏览器到第三方应用的回调url(redirect_uri), * 并附上code,openid和openkey等參数 * http://www.newer.com/ * #access_token=789a7d5284d0c3e608f8e384c993d04b * &expires_in=8035200 * &openid=0027BC08DB5B45D7461E9A0F16F527E7 * &openkey=60A1DF40C01EE30537AF7739504DFDB0 * &refresh_token=5c768f8850ae5af2193ce79f3f0a1351 * &state= * &name=cfloat656805 * &nick=Cfloat */ if(url.startsWith(TencentAPI.redirectUri)){ //推断回调的Url前缀是否是你授权时给的url地址 /*截取:access_token=789a7d5284d0c3e608f8e384c993d04b * &expires_in=8035200 * &openid=0027BC08DB5B45D7461E9A0F16F527E7 * &openkey=60A1DF40C01EE30537AF7739504DFDB0 * &refresh_token=5c768f8850ae5af2193ce79f3f0a1351 * &state= * &name=cfloat656805 * &nick=Cfloat */ String text = url.substring(url.indexOf("#")+1) ; String[] params = text.split("&") ; SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit() ; for(String str : params){ Log.i("遍历正则取到的參数:", str+" ") ; String[] KeyValue = str.split("=") ; //切割 if(KeyValue.length == 2){ editor.putString(KeyValue[0], KeyValue[1]) ; } Log.i("存放到首选项的2个參数:", Arrays.toString(KeyValue)) ; } editor.commit() ; //提交 startActivity(new Intent(getApplication(),MainActivity.class)); finish(); //结束 } }; } ;}

OK,前期的工作已经KO了,以下说说access_token凭证,他的有效时间是30天,假设出现key与凭证不匹配的情况下,能够卸载应用,或者将凭证刷新,就可以解决失效与不匹配的问题了。好了,第一篇就到这吧!

谢谢~~

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/116333.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(2)
blank

相关推荐

  • linux 修改文件权限命令_linux给权限命令

    linux 修改文件权限命令_linux给权限命令查看文件权限ls-h命令修改文件权限修改方法1:(参数)命令:chomod语法:chomod[参数][augo][+-=][rwx]文件名例子:1.将文件file1.txt增加可读权限chmodugo+rfile1.txt2.将文件file1.txt设为所有人(all)可读chmoda=rfile1.txt3.为ex1.py文件拥有者取消可执行权限chmodu-xex1.py修改方法2:(数字)命令:chmod语法..

  • Proxool线程池的简单实现demo

    Proxool线程池的简单实现demo

  • PHP json_decode[通俗易懂]

    PHP json_decode[通俗易懂]json_decode(PHP5>=5.2.0,PECLjson>=1.2.0)json_decode — 对JSON格式的字符串进行编码说明 ¶mixed json_decode ( string $json [, bool $assoc =false [, int $depth =512 [, int $options =0 

  • 邮箱正则表达式

    邮箱正则表达式正则提取国内外所有的邮箱经过测试准确率100%python代码块res=re.search(r’\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,8}\b’,description)ifres:emailAddress=res.group()else:emailAddr…

  • 解决FileSystemWatcher事件多次触发的方法

    解决FileSystemWatcher事件多次触发的方法

  • poe交换机是干什么用的_poe交换机

    poe交换机是干什么用的_poe交换机供电用的交换机,比如安装网络监控时不方便给摄像头拉电线,就可以使用PoE交换机供电,还有弄无线网络时也可以给AP供电,主要方便,关于怎么使用,如果那些需要供电的设备支持PoE直接连接就行了。那么,什么叫POE交换机?POE交换机怎么使用呢?接下来我们就跟随飞畅科技的小编一起来详细了解下吧!交换机操作步骤:第一步:将ADSL猫的网线连接到以太网交换机任意一个口;第二步:设置笔记本的其中一台,IP(也可以是其他的),然后设置子网掩码,默认即可,其他信息一概不填;第三步:用系统自带的宽带连接建立好

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号