android网络获取json数据格式化,android获取网络新版本数据(json格式)并显示Demo

  • Post author:
  • Post category:其他


package zz.itcast.mobileSafe.activity;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import zz.itcast.mobileSafe.utils.StreamUtils;

import android.app.Activity;

import android.content.pm.PackageInfo;

import android.content.pm.PackageManager;

import android.content.pm.PackageManager.NameNotFoundException;

import android.os.Bundle;

import android.util.Log;

import android.widget.TextView;

@SuppressWarnings(“unused”)

public class SplashActivity extends Activity {

private TextView tv_version;

private String versionName;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

intiViews();

tv_version.setText(“版本名” getVersionName());

checkVersion();

}

private void intiViews() {

tv_version = (TextView) findViewById(R.id.tv_version);

}

private String getVersionName() {

PackageManager packageManager = getPackageManager();

try {

PackageInfo packageInfo = packageManager.getPackageInfo(

getPackageName(), 0);

versionName = packageInfo.versionName;

int versionCode = packageInfo.versionCode;

System.out.println(versionCode “—” versionName);

} catch (NameNotFoundException e) {

e.printStackTrace();

}

return versionName;

}

private void checkVersion() {

// 进行联网操作,因为是耗时操作,需要放在子线程中去做

new Thread(new Runnable() {

@Override

public void run() {

try {

URL url = new URL(“http://192.168.149.2:8080/update.json”);

try {

HttpURLConnection conc = (HttpURLConnection) url

.openConnection();

conc.setConnectTimeout(5000);

conc.setRequestMethod(“GET”);

conc.setReadTimeout(5000);

conc.connect();

int code = conc.getResponseCode();

if(code==200){

//连接成功,获取输入流

InputStream stream = conc.getInputStream();

String result = StreamUtils.StreamToString(stream);

Log.d(“网络结果”, result);

}

} catch (IOException e) {

e.printStackTrace();

}

} catch (MalformedURLException e) {

e.printStackTrace();

}

}

}).start();

}

}

需3积分下载

https://www.codedown123.com/34043.html