Android学习小结

近来由于公司赶项目,好久没写这种博客了,本来想在原有的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;

}

}

你可能感兴趣的:(Android学习小结)