Android 프로그래밍의 제3자 개발MaoZhuaWeiBo 마이크로블로그 개발 예-1

29770 단어
대학 시절에 저는 이런 앱을 많이 만들었습니다. 이것은 저희 팀에서 전에 한 것입니다. 저는 후기에 새로운 요소를 많이 넣어서 이 앱을 보완했습니다. 왜냐하면 이 앱을 강화하기 위해서입니다.
전문 기술도 그렇고 밤을 새워 작은 글을 많이 씁니다. 헤헤, 그래도 괜찮은 편이에요. 적어도 기술이 많이 늘었잖아요. 그래도 뿌듯해요. 오늘 여러분께 텐센트를 알려드릴게요.
웨이보 제3자는 클라이언트 개발을 확대한다. 말하자면 제3자 인터페이스를 사용하는 개방 플랫폼을 이용하여 2차 개발을 하는 것이다. 위챗과 약간 유사하지. 됐어, 그만해. 당장.
본론으로 들어가겠습니다.
개발 전 준비:
① 텐센트 QQ번호(모두가 가지고 있을 거라 믿는다) ② 텐센트 웨이보 앱키(신청 주소: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));
		 }
	 }

	
	

}

우리 아이유가 너무 못 써서...레이아웃 파일은...,관심 있으면 원본 코드를 보세요. 이 앱을 설명하고 나서 붙여드릴게요.
다음은 증거로 캡처한 각자의 결과 캡처, 코드에 대해 말씀드리겠습니다.
캡처 성공:
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+"
"+ "openid :" + openid +"
"+ "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) ; // 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()+" :

"); 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; } }

결과도, 개인정보 인터페이스, 네트워크 캡처, 해석, 네트워크가 없을 때 마지막으로 동적 데이터를 로컬에 저장:
데이터는 모두 텐센트 서버에서 온 것이지 로컬이 아니다. 첫 페이지 인터페이스:
이 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
			 *                                      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가 되었으니 다음에accessToken 증명서, 그의 유효시간은 30일입니다. 키와 증명서가 일치하지 않는 경우 앱을 마운트 해제하거나 증명서를 갱신하면 실효와 일치하지 않는 문제를 해결할 수 있습니다. 자, 첫 번째 편은 여기까지입니다!감사합니다~~

좋은 웹페이지 즐겨찾기