近來由于公司趕項目,好久沒寫這種博客了,本來想在原有的csdn上寫的,不知道為什么csdn跳轉老是失敗,所以就找了簡書這個好平臺來了。? ??
? http://blog.csdn.net/qq_29158381
先從http網絡請求開始寫起好了,以下是我工作中封裝的http網絡請求工具類,要用get請求就直接調用getDataByGet(String url)方法即可,要用post請求就直接調用getDataByPost(String url,String parms) ?當然,里面的邏輯處理要你們自己寫,我這里返回的都是String類型,用于公司接口的json解析,具體解析什么的到時填寫在里面即可
/*http請求工具類*/
public class NetUtil {
private static NetUtil instance;
private NetUtil() {}
public synchronized static NetUtil getInstance() {
if (null == instance) {
instance = new NetUtil();
}
return instance;
}
//http-->get ? ?獲取字符串
public String getDataByGet(String url) {
try {
String jsonString=readStream(new URL(url).openStream());
JSONObject jsonObject=new JSONObject(jsonString);
String json=jsonObject.getString("data");
return json;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//http-->post ? 獲取字符串
public String getDataByPost(String url,String parms){
try {
String jsonString=readStream(sendPost(url, parms));
JSONObject jsonObject=new JSONObject(jsonString);
String json=jsonObject.getString("data");
return json;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//得到post請求后的輸入流
public InputStream sendPost(String url,String params){
URL mURL=null;
InputStream in=null;
HttpURLConnection conn=null;
try {
mURL=new URL(url);
conn=(HttpURLConnection) mURL.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
PrintWriter pw=new PrintWriter(conn.getOutputStream());
pw.print(params);
pw.flush();
pw.close();
in=conn.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return in;
}
//將輸入流中的文本提取出來
private String readStream(InputStream is){
InputStreamReader isr;
String result="";
try {
String line="";
isr=new InputStreamReader(is,"utf-8");
BufferedReader br=new BufferedReader(isr);
while((line=br.readLine())!=null){
result+=line;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
網絡加載圖片-----glide與picasso的使用
glide篇
Glide.with(context).load(url).error(R.drawable.error_img).into(img_view);
glide在適配器中若要進行復用,要設置標志,不然報錯:
? ? ? ? ?v.setTag(R.string.app_name,holder);->?holder=(ViewHolder) v.getTag(R.string.app_name);
picasso篇
Picasso.with(context).load(url).error(R.drawable.error_img).into(img_view);
? ? ?picasso性能不如glide,但是如果glide使用過程中出現錯誤,一時解決不了的話就暫時先用Picasso代替一下吧
注意:這里的圖片加載統統要在分線程中進行
判斷是否接入網絡
public boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
發送短信倒計時60s實現
public class MyCountTimer extends CountDownTimer {
public static final int TIME_COUNT = 61000;//時間防止從59s開始顯示
private TextView btn;
private String endStrRid;
private int normalColor, timingColor;//未計時的文字顏色,計時期間的文字顏色
/**
* 參數 millisInFuture? ? ? ? 倒計時總時間
* 參數 countDownInterval? ? 漸變時間(每次倒計1s)
* 參數 btn? ? ? ? ? ? ? 點擊的按鈕(因為Button是TextView子類,為了通用我的參數設置為TextView)
* 參數 endStrRid? 倒計時結束后,按鈕對應顯示的文字
*/
public MyCountTimer (long millisInFuture, long countDownInterval, TextView btn, String endStrRid) {
super(millisInFuture, countDownInterval);
this.btn = btn;
this.endStrRid = endStrRid;
}
/**
*參數上面有注釋
*/
public? MyCountTimer (TextView btn, String endStrRid) {
super(TIME_COUNT, 1000);
this.btn = btn;
this.endStrRid = endStrRid;
}
public MyCountTimer (TextView btn) {
super(TIME_COUNT, 1000);
this.btn = btn;
this.endStrRid = "重新發送";
}
public MyCountTimer (TextView tv_varify, int normalColor, int timingColor) {
this(tv_varify);
this.normalColor = normalColor;
this.timingColor = timingColor;
}
// 計時完畢時觸發
@Override
public void onFinish() {
if(normalColor > 0){
btn.setTextColor(normalColor);
}
btn.setText(endStrRid);
btn.setEnabled(true);
btn.setBackgroundResource(R.drawable.icon_getcode);
}
// 計時過程顯示
@Override
public void onTick(long millisUntilFinished) {
if(timingColor > 0){
btn.setTextColor(timingColor);
}
btn.setEnabled(false);
btn.setText(millisUntilFinished / 1000 + "s");
}
}
txtview.setBackgroundResource(R.drawable.icon_getcode0);
MyCountTimer timeCount = new MyCountTimer(txtview);// 傳入了文字顏色值
timeCount.start();
更新客戶端工具類
public class UpdateManager {
private Context mContext;
//提示語
private String updateMsg = "有最新的軟件包哦,快來下載吧~";
//返回的安裝包url
private String apkUrl = "http://www.enuo120.com/Public/download/enuo.apk";
private Dialog noticeDialog;
private Dialog downloadDialog;
/* 下載包安裝路徑 */
private static final String savePath = "/sdcard/Download/";
private static final String saveFileName = savePath + "enuo.apk";
/* 進度條與通知ui刷新的handler和msg常量 */
private ProgressBar mProgress;
private static final int DOWN_UPDATE = 1;
private static final int DOWN_OVER = 2;
private int progress;
private Thread downLoadThread;
private boolean interceptFlag = false;
private Handler mHandler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what) {
case DOWN_UPDATE:
mProgress.setProgress(progress);
break;
case DOWN_OVER:
installApk();
break;
default:
break;
}
};
};
public UpdateManager(Context context) {
this.mContext = context;
}
//外部接口讓主Activity調用
public void checkUpdateInfo(){
showNoticeDialog();
}
private void showNoticeDialog(){
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle("軟件版本更新");
builder.setMessage(updateMsg);
builder.setPositiveButton("下載更新", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
showDownloadDialog();
}
});
builder.setNegativeButton("以后再說", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
noticeDialog = builder.create();
noticeDialog.show();
}
private void showDownloadDialog(){
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle("軟件版本更新");
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.progress, null);
mProgress = (ProgressBar)v.findViewById(R.id.progress);
builder.setView(v);
builder.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
interceptFlag = true;
}
});
downloadDialog = builder.create();
downloadDialog.setCanceledOnTouchOutside(false);// 設置點擊屏幕Dialog不消失
downloadDialog.show();
downloadApk();
}
private Runnable mdownApkRunnable = new Runnable() {
@Override
public void run() {
try {
URL url = new URL(apkUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
File file = new File(savePath);
if(!file.exists()){
file.mkdir();
}
String apkFile = saveFileName;
File ApkFile = new File(apkFile);
FileOutputStream fos = new FileOutputStream(ApkFile);
int count = 0;
byte buf[] = new byte[1024];
do{
int numread = is.read(buf);
count += numread;
progress =(int)(((float)count / length) * 100);
//更新進度
mHandler.sendEmptyMessage(DOWN_UPDATE);
if(numread <= 0){
//下載完成通知安裝
mHandler.sendEmptyMessage(DOWN_OVER);
break;
}
fos.write(buf,0,numread);
}while(!interceptFlag);//點擊取消就停止下載.
fos.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
};
/**
* 下載apk
* @param url
*/
private void downloadApk(){
downLoadThread = new Thread(mdownApkRunnable);
downLoadThread.start();
}
/**
* 安裝apk
* @param url
*/
private void installApk(){
File apkfile = new File(saveFileName);
if (!apkfile.exists()) {
return;
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
mContext.startActivity(i);
}
/**
* 獲取版本號
* @return 當前應用的版本號
*/
public String getVersion() {
try {
PackageManager manager = mContext.getPackageManager();
PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
return info.versionName;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}