消息机制:
1. XML文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_demo_number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="10"
android:textColor="#ff0000"
android:textSize="20sp"/>
<Button
android:id="@+id/btn_demo_increase"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="自动增加" />
<Button
android:id="@+id/btn_demo_decrease"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="自动减少" />
<Button
android:id="@+id/btn_demo_pause"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="暂停"
android:enabled="false"/>
</LinearLayout>
2. Activity文件
public class HandlerDemoActivity extends Activity implements OnClickListener {
private static final int WHAT_INCREASE = 1;
private static final int WHAT_DECREASE = 2;
private TextView tv_demo_number;
private Button btn_demo_increase;
private Button btn_demo_decrease;
private Button btn_demo_pause;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
//得到当前显示的数值
int number = Integer.parseInt(tv_demo_number.getText().toString());
switch (msg.what) {
case WHAT_INCREASE:
//限制number<=20
if(number==20) {
//设置暂停不能操作
btn_demo_pause.setEnabled(false);
Toast.makeText(HandlerDemoActivity.this, "已经达到最大值", 0).show();
return;
}
number++;
tv_demo_number.setText(number+"");
//发送增加的延迟消息
handler.sendEmptyMessageDelayed(WHAT_INCREASE, 1000);
break;
case WHAT_DECREASE:
//限制number>=1
if(number==1) {
//设置暂停不能操作
btn_demo_pause.setEnabled(false);
Toast.makeText(HandlerDemoActivity.this, "已经达到最小值", 0).show();
return;
}
number--;
tv_demo_number.setText(number+"");
//发送减少的延迟消息
handler.sendEmptyMessageDelayed(WHAT_DECREASE, 1000);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler_demo);
init();
}
private void init() {
tv_demo_number = (TextView) findViewById(R.id.tv_demo_number);
btn_demo_increase = (Button) findViewById(R.id.btn_demo_increase);
btn_demo_decrease = (Button) findViewById(R.id.btn_demo_decrease);
btn_demo_pause = (Button) findViewById(R.id.btn_demo_pause);
btn_demo_increase.setOnClickListener(this);
btn_demo_decrease.setOnClickListener(this);
btn_demo_pause.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v==btn_demo_increase) {//自动增加 what =1
//限制Button可操作性
btn_demo_increase.setEnabled(false);
btn_demo_decrease.setEnabled(true);
btn_demo_pause.setEnabled(true);
//停止减少(移除未处理的减少的消息)
handler.removeMessages(WHAT_DECREASE);
//发消息(增加)
handler.sendEmptyMessage(WHAT_INCREASE);
} else if(v==btn_demo_decrease) {//自动减少 what=2
//限制Button可操作性
btn_demo_increase.setEnabled(true);
btn_demo_decrease.setEnabled(false);
btn_demo_pause.setEnabled(true);
//停止增加(移除未处理的增加的消息)
handler.removeMessages(WHAT_INCREASE);
//发消息(减少)
handler.sendEmptyMessage(WHAT_DECREASE);
} else if(v==btn_demo_pause) {//暂停
//限制Button可操作性
btn_demo_increase.setEnabled(true);
btn_demo_decrease.setEnabled(true);
btn_demo_pause.setEnabled(false);
//停止增加/减少(移除未处理的减少/增加的消息)
handler.removeMessages(WHAT_INCREASE);
handler.removeMessages(WHAT_DECREASE);
}
}
}
异步任务:
1. XML文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.atguigu.l04_app3.MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="35dp"
android:text="下载最新版本APK"
android:onClick="downloadApk"/>
</RelativeLayout>
2. Activity文件
public class AsyncTaskTestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async);
}
private File apkFile;
private ProgressDialog dialog;
public void downloadApk(View v) {
//启动异步任务处理
new AsyncTask<Void, Integer, Void>() {
//1. 主线程, 显示提示视图
protected void onPreExecute() {
dialog = new ProgressDialog(AsyncTaskTestActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.show();
//准备用于保存APK文件的File对象 : /storage/sdcard/Android/package_name/files/xxx.apk
apkFile = new File(getExternalFilesDir(null), "update.apk");
}
//2. 分线程, 联网请求
@Override
protected Void doInBackground(Void... params) {
try {
//1. 得到连接对象
String path = "http://192.168.10.165:8080/Web_Server/L04_DataStorage.apk";
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//2. 设置
//connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(10000);
//3. 连接
connection.connect();
//4. 请求并得到响应码200
int responseCode = connection.getResponseCode();
if(responseCode==200) {
//设置dialog的最大进度
dialog.setMax(connection.getContentLength());
//5. 得到包含APK文件数据的InputStream
InputStream is = connection.getInputStream();
//6. 创建指向apkFile的FileOutputStream
FileOutputStream fos = new FileOutputStream(apkFile);
//7. 边读边写
byte[] buffer = new byte[1024];
int len = -1;
while((len=is.read(buffer))!=-1) {
fos.write(buffer, 0, len);
//8. 显示下载进度
//dialog.incrementProgressBy(len);
//在分线程中, 发布当前进度
publishProgress(len);
//休息一会(模拟网速慢)
//Thread.sleep(50);
SystemClock.sleep(50);
}
fos.close();
is.close();
}
//9. 下载完成, 关闭, 进入3)
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//3. 主线程, 更新界面
protected void onPostExecute(Void result) {
dialog.dismiss();
installAPK();
}
//在主线程中更新进度(在publishProgress()之后)
protected void onProgressUpdate(Integer[] values) {
dialog.incrementProgressBy(values[0]);
}
}.execute();
//int Integer float Float void Void
}
/**
* 启动安装APK
*/
private void installAPK() {
Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE");
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
startActivity(intent);
}
}
JSon数据解析:
/*
1. 将json格式的字符串{}转换为Java对象, 使用原生API
2. 将json格式的字符串{}转换为Java对象, 使用GSON
3. 将json格式的字符串[]转换为Java对象的List, 使用原生API
4. 将json格式的字符串[]转换为Java对象的List, 使用GSON
5. 将Java对象转换为json字符串{}, 使用GSON
6. 将Java对象的List转换为json字符串[], 使用GSON
*/
public class JsonTest extends AndroidTestCase{
/*
* 1. 将json格式的字符串{}转换为Java对象, 使用原生API
*/
public void testJsonToObject() throws JSONException {
String jsonString = "{\"id\":2, \"name\":\"大虾\", \"price\":12.3,\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"}";
//将json字符串封装为JSONObject对象
JSONObject jsonObject = new JSONObject(jsonString);
//从对象中根据key得到对应的value
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
double price = jsonObject.getDouble("price");
String imagePath = jsonObject.getString("imagePath");
//封装ShopInfo对象
ShopInfo shopInfo = new ShopInfo(id, name, price, imagePath);
Log.e("TAG", shopInfo.toString());
}
/*
* 1. 将json格式的字符串{}转换为Java对象, 使用GSON
*/
public void testJsonToObject2() {
String jsonString = "{\"id\":3, \"name\":\"大虾\", \"price\":12.3,\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"}";
ShopInfo shopInfo = new Gson().fromJson(jsonString, ShopInfo.class);
Log.e("TAG", shopInfo.toString());
}
/*
* 3. 将json格式的字符串[]转换为Java对象的List, 使用原生API
*/
public void testJsonToList() throws JSONException {
String jsonString = "[{\"id\":3, \"name\":\"大虾\", \"price\":12.3,\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"},"
+ "{\"id\":5, \"name\":\"大虾2\", \"price\":128.3,\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f2.jpg\"}]";
List<ShopInfo> list = new ArrayList<ShopInfo>();
//1. 将json字符串包装JSONArray对象
JSONArray jsonArray = new JSONArray(jsonString);
//2. 遍历JSONArray对象所有元素(JSONObject), 并将每个元素封装为shopInfo, 并添加到List
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//从对象中根据key得到对应的value
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
double price = jsonObject.getDouble("price");
String imagePath = jsonObject.getString("imagePath");
//封装ShopInfo对象
ShopInfo shopInfo = new ShopInfo(id, name, price, imagePath);
list.add(shopInfo);
}
Log.e("TAG", list.toString());
}
/*
* 4. 将json格式的字符串[]转换为Java对象的List, 使用GSON
*/
public void testJsonToList2() throws JSONException {
String jsonString = "[{\"id\":4, \"name\":\"大虾\", \"price\":12.3,\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"},"
+ "{\"id\":6, \"name\":\"大虾2\", \"price\":128.3,\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f2.jpg\"}]";
List<ShopInfo> list = new Gson().fromJson(jsonString, new TypeToken<List<ShopInfo>>(){}.getType());
Log.e("TAG", list.toString());
}
/*
5. 将Java对象转换为json字符串{}, 使用GSON
*/
public void testObjectToJson() {
ShopInfo info = new ShopInfo(3, "KK", 1000, "http://www.sina.com");
String json = new Gson().toJson(info);
Log.e("TAG", json);
}
/*
6. 将Java对象的List转换为json字符串[], 使用GSON
*/
public void testListToJson() {
List<ShopInfo> list = new ArrayList<ShopInfo>();
list.add(new ShopInfo(3, "KK", 1000, "http://www.sina.com"));
list.add(new ShopInfo(4, "KK2", 2000, "http://www.sina.com222"));
String json = new Gson().toJson(list);
Log.e("TAG", json);
}
public void testJsonToMap() {
String jsonString = "{\"my name\":\"大虾\", \"1\":12}";
Map<String, Object> map = new Gson().fromJson(jsonString, new TypeToken<Map<String, Object>>(){}.getType());
Log.e("TAG", map.toString());
}
}