1.ApacheHttpClient_Get請求
package com.recycler.zx.zxrecyclerview.ApacheHttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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 java.io.IOException;
/**
* Created by zx on 2015/12/24.
* get:大小不超過4kb,速度快,參數會在URL上面顯示,不安全
* post:大小不限制,速度比get慢,參數不會在URL上顯示,安全性高
*/
public class ApacheHttpClientGet {
public static void httpGet(final String path){
new Thread(new Runnable() {
@Override
public void run() {
HttpGet get = new HttpGet(path);
//建立http用戶端對象,用于發送請求
HttpClient httpClient = new DefaultHttpClient();
try {
//向伺服器發送請求,并傳回響應對象
HttpResponse response = httpClient.execute(get);
//擷取響應狀态碼
int status = response.getStatusLine().getStatusCode();
switch (status) {
case HttpStatus.SC_OK :
//200
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity,"utf-8");
break;
case HttpStatus.SC_NOT_FOUND :
//404
break;
case HttpStatus.SC_INTERNAL_SERVER_ERROR :
//500
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
2.ApacheHttpClient_Post請求
package com.recycler.zx.zxrecyclerview.ApacheHttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.lang.reflect.Array;
import java.util.ArrayList;
/**
* Created by zx on 2015/12/24.
*/
public class ApacheHttpClientPost {
public static void httpPost(final String path){
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpPost httpPost = new HttpPost(path);
//建立http用戶端對象,用于發送請求
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name","jack"));
params.add(new BasicNameValuePair("sex","nan"));
HttpEntity entity = new UrlEncodedFormEntity(params);
httpPost.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
//向伺服器發送請求,并傳回響應對象
HttpResponse response = httpClient.execute(httpPost);
//擷取響應狀态碼
int status = response.getStatusLine().getStatusCode();
switch (status) {
case HttpStatus.SC_OK :
//
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity,"utf-8");
break;
case HttpStatus.SC_NOT_FOUND :
//
break;
case HttpStatus.SC_INTERNAL_SERVER_ERROR :
//
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
3.Volley和android-Async-http和okhttp
Volley:
優點:頻繁通信适合
缺點:大檔案下載下傳上傳不是很擅長
android-Async-http:(這個開源項目已經很老了,它的fork比較多,也是因為在3,4年前出現的
出現的比較早,在前幾年它可能是比較好用的,并且它的httpClient和Apatch中httpClient是不一樣的;
Apatch已經更新了httpClient,而它還用的是以前版本的httpClient,不得不說它也不再流行了)
優點:下載下傳上傳擅長有API
缺點:目前不知道
目前最佳:Volley+okhttp
Android Studio的gradle依賴
你需要在app子產品的build.gradle檔案中添加如下幾行代碼:
compile ‘com.squareup.okio:okio:1.5.0’
compile ‘com.squareup.okhttp:okhttp:2.4.0’
compile ‘com.mcxiaoke.volley:library:1.0.16’
compile ‘com.google.code.gson:gson:2.3.1’
以上幾個依賴都是官方的,雖然Volley不是官方提供的,但是也值得信賴
來源: http://www.open-open.com/lib/view/open1437532961428.html
4.android-async-http上傳下載下傳
上傳檔案的3中方式:其實最終都是轉換成流了
5.WebService
package com.recycler.zx.zxrecyclerview.volleyAndAsyncAndWebservice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.recycler.zx.zxrecyclerview.R;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import java.lang.ref.WeakReference;
import butterknife.Bind;
import butterknife.ButterKnife;
public class WebServiceActivity extends AppCompatActivity {
@Bind(R.id.button4)
Button button4;
private MyHandler myHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_service);
ButterKnife.bind(this);
}
public void webServiceClick(View v) {
myHandler = new MyHandler(this);
new Thread(new Runnable() {
@Override
public void run() {
getTelephoneInfo("13888888888");
}
}).start();
}
private static class MyHandler extends Handler {
private WeakReference<WebServiceActivity> mWeakReference;
private WebServiceActivity mActivity;
public MyHandler(WebServiceActivity activity) {
mWeakReference = new WeakReference<WebServiceActivity>(activity);
mActivity = mWeakReference.get();
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (mActivity != null) {
String result = (String) msg.obj;
mActivity.button4.setText(result);
}
}
}
public void getTelephoneInfo(String phone_number) {
//命名空間
String nameSpace = "http://WebXml.com.cn/";
//調用的方法名稱
String methodName = "getMobileCodeInfo";
// webservice的網址
String URL = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
//命名空間+方法
String soapAction = "http://WebXml.com.cn/getMobileCodeInfo";
// 指定WebService的命名空間和調用的方法名
SoapObject rpc = new SoapObject(nameSpace, methodName);
// 設定需調用WebService接口需要傳入的兩個參數mobileCode、userId
rpc.addProperty("mobileCode", phone_number);
rpc.addProperty("userId", "");
// 生成調用WebService方法的SOAP請求資訊,并指定SOAP的版本
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
envelope.bodyOut = rpc;
// 設定是否調用的是dotNet開發的WebService
envelope.dotNet = true;
// 等價于
/* envelope.bodyOut = rpc;
envelope.setOutputSoapObject(rpc);*/
HttpTransportSE transport = new HttpTransportSE(URL);
try {
// 調用WebService
transport.call(soapAction, envelope);
} catch (Exception e) {
e.printStackTrace();
}
// 擷取傳回的資料
SoapObject object = (SoapObject) envelope.bodyIn;
// 擷取傳回的結果
String result = object.getProperty().toString();
Message msg = myHandler.obtainMessage();
msg.obj = result;
myHandler.sendMessage(msg);
}
}
6.WebView與js互動
private void initWebView() {
WebSettings settings = wvList.getSettings();
settings.setJavaScriptEnabled(true);
settings.setBuiltInZoomControls(true);
wvList.requestFocus();
wvList.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//設定點選連結在webview中顯示
wvList.setWebViewClient(new WebViewClient());
wvList.setWebChromeClient(new WebChromeClient());
//wvList.loadUrl("http://www.baidu.com/");
myHandler = new MyHandler(this);
wvList.addJavascriptInterface(new myObj(),"myweb");
wvList.loadUrl("file:///android_asset/html/index.html");
}
public class myObj{
@JavascriptInterface
public void toWeb(){
myHandler.post(new Runnable() {
@Override
public void run() {
wvList.loadUrl("javascript:myfun()");
}
});
}
}
<html hljs-string">"en">
<head>
<title>Document</title>
<script language="JavaScript">
function myfun(){
document.getElementById("imgId").src="b.jpg";
}
</script>
</head>
<body>
<a onclick="window.myweb.toWeb()">
<img src="a.jpg" id="imgId" />
</a>
</body>
</html>
7.屬性動畫和視圖動畫(tween(補間動畫),frame(幀動畫))
package com.recycler.zx.zxrecyclerview.tweenAndframe;
import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.widget.ImageView;
import android.widget.Toast;
import com.recycler.zx.zxrecyclerview.R;
import butterknife.Bind;
import butterknife.ButterKnife;
//android 中的動畫注意:視圖動畫:animation(動畫),屬性動畫:animator(動畫繪制者)
public class AnimationsActivity extends AppCompatActivity {
@Bind(R.id.iv_tween)
ImageView ivTween;
@Bind(R.id.iv_frame)
ImageView ivFrame;
@Bind(R.id.iv_attribute)
ImageView ivAttribute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animations);
ButterKnife.bind(this);
}
//**************************************************************************************************視圖動畫
public void tween(View v) {
//1.xml中建立動畫 alpha_anim.xml//漸漸消失
Animation animation = AnimationUtils.loadAnimation(this, R.anim.rotate_anim);
ivTween.startAnimation(animation);
//2.直接在程式中建立動畫
// Animation animation2 = new AlphaAnimation(0.0f,1.0f);
//ivAnim.startAnimation(animation2);
}
public void frame(View v) {
AnimationDrawable animation = (AnimationDrawable) ivFrame.getDrawable();
animation.start();
}
//**************************************************************************************************屬性動畫
//屬性動畫有代碼實作和xml實作2中
//屬性動畫,,用的最多,下面先代碼實作再xml實作(xml中屬性動畫在animator檔案夾中,視圖動畫是在anim檔案夾中)
public void attribute(View v) {
ObjectAnimator
.ofFloat(ivAttribute, "rotationx", f, f)
.setDuration().start();
}
public void propertyValuesHolder(View v){
//ObjectAnimator
/*PropertyValuesHolder phx = PropertyValuesHolder.ofFloat("alpha",1f,0f,1f);
PropertyValuesHolder phy = PropertyValuesHolder.ofFloat("scaleX",1f,0,1f);
PropertyValuesHolder phz = PropertyValuesHolder.ofFloat("scaleY",1f,0,1f);
ObjectAnimator.ofPropertyValuesHolder(v,phx,phy,phz).setDuration(5000).start();*/
//ValueAnimator
final View view = v;
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
//定義一個動畫
ValueAnimator anim = ValueAnimator.ofFloat(v.getX(),dm.widthPixels+v.getWidth(),v.getX()).setDuration();
//監聽動畫的每個動作
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){
@Override
public void onAnimationUpdate(ValueAnimator animation) {
view.setTranslationX((Float) animation.getAnimatedValue());
}
});
anim.start();
}
public void animListener(final View v){
//1f:開始,0f:結束
ObjectAnimator anim = ObjectAnimator.ofFloat(v,"alpha",f,f).setDuration();
anim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
//動畫開始
}
@Override
public void onAnimationEnd(Animator animation) {
//動畫結束
ViewGroup vg = (ViewGroup) v.getParent();
if(vg != null) {
vg.removeView(v);
Toast.makeText(AnimationsActivity.this,"已删除view",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onAnimationCancel(Animator animation) {
//取消動畫
}
@Override
public void onAnimationRepeat(Animator animation) {
//重複播放
}
});
//上面的方法比較麻煩,如果你隻想使用onAnimationEnd(其中一個方法就不友善)
// 可以直接使用監聽擴充卡,實作單個方法,比較靈活
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
//動畫結束
ViewGroup vg = (ViewGroup) v.getParent();
if(vg != null) {
vg.removeView(v);
Toast.makeText(AnimationsActivity.this,"已删除view",Toast.LENGTH_SHORT).show();
}
}
});
anim.start();
}
//排序播放動畫,不是同時播發,(比如,先播發a動畫,再播放b動畫)
public void animSet(View v){
ObjectAnimator oax = ObjectAnimator.ofFloat(v,"translationX",f,f);
ObjectAnimator oay = ObjectAnimator.ofFloat(v,"translationY",f,f);
ObjectAnimator oarotation = ObjectAnimator.ofFloat(v,"rotation",f,f);
AnimatorSet set = new AnimatorSet();
set.setDuration();
//排序設定
//set.playTogether(oax,oay,oarotation);//3個動畫同時執行
//set.playSequentially(oay,oax,oarotation);//按參數順序執行
//set.setStartDelay(300);//延遲執行
//oax,oay同時執行,之後執行oarotation
set.play(oax).with(oay);
set.play(oarotation).after(oay);
set.start();
//注意:不能set.play(oax).with(oay).after().before()連接配接太長
}
/* 插值器,就是告訴Android,播放動畫時
是從快到慢還是從慢到快,從左到右的旋轉還是其它的方式的動畫,
類型如下面的八種,跟scale.xml或alpha.xml中使用的插值器一樣的,隻是寫的形式不一樣而已
所有的插值器都實作Interpolator接口中的 getInterpolation(float input)方法,
注意一點,插值器不能同時set多個,不然最前面的會被覆寫,即:無效果..
/* new AccelerateDecelerateInterpolator();
* new AccelerateInterpolator();
* new CycleInterpolator(1.0f);
* new DecelerateInterpolator();
* new AnticipateInterpolator();
* new AnticipateOvershootInterpolator();
* new BounceInterpolator();
* new OvershootInterpolator();
* new LinearInterpolator();
* 與以上幾種插值器相對應的方法在xml檔案中的使用方式大家可以自動ALT+/試下,換湯不換藥
*/
public void interpolators(View v){
ObjectAnimator oax = ObjectAnimator.ofFloat(v,"translationX",f,f);
ObjectAnimator oay = ObjectAnimator.ofFloat(v,"translationY",f,f);
ObjectAnimator oarotation = ObjectAnimator.ofFloat(v,"rotation",f,f);
AnimatorSet set = new AnimatorSet();
set.playTogether(oax,oay,oarotation);//3個動畫同時執行
//插值器不能同時set多個
set.setInterpolator(new BounceInterpolator());
set.setDuration();
set.start();
}
public void attributeAnimator(View v){
Animator animator = AnimatorInflater.loadAnimator(this,R.animator.alpha);
/*v.setPivotX(0);
v.setPivotY(0);
//如果調用了pivot設定了位置,就必須調用invalidate更新一下
v.invalidate();*/
animator.setTarget(v);
animator.start();
}
}
8.插值器常用方法
9.畫布與繪制 ,幾何圖形與繪制
平常開發用的比較少,具體可以去搜尋Canvas
繪制圖檔到畫布上面,一般用于自定義view和遊戲
package com.recycler.zx.zxrecyclerview.tweenAndframe;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
import com.recycler.zx.zxrecyclerview.R;
/**
* Created by zx on 2015/12/22.
*/
public class BitmapView extends View {
public BitmapView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
Bitmap bp = BitmapFactory.decodeResource(getResources(), R.mipmap.a);
canvas.drawBitmap(bp,,,paint);
}
}
surfaceView用獨立的線程來進行繪制, 是以可以提供更多的幀率
一般用于遊戲