前言:
平时,我们玩手机的时候,点击按钮,肉眼可见页面发生了变化。不要小看这小小的变化,底层通过了多层的网络传输(具体需要学习计算机网络),本篇将通过TCP(传输层)/IP(网络层),调用Socket(会话层)实现通信。
⭐注意事项
- sleep不能在主线程(UI线程),要另起一个线程
- 网络访问不能在主线程(UI线程),要另起一个线程
- 修改控件必须要在主线程(UI线程),不能在其他线程
简易Android客户端
编写一个简易的方向盘Android客户端:
activity_main.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=".MainActivity" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" "
android:layout_centerInParent="true" />
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/text"
android:layout_centerHorizontal="true"
android:onClick="Send"
android:text="前进" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/text"
android:layout_centerHorizontal="true"
android:onClick="Send"
android:text="后退" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/text"
android:layout_centerVertical="true"
android:onClick="Send"
android:text="左转" />
<Button
android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content