实战篇——Android之Socket客户端编程

本文介绍了Android中使用Socket进行客户端编程的实践,强调了网络操作不在主线程的重要性,并展示了简易客户端、倒计时闹钟及综合案例的实现过程,通过实际代码解释了如何与服务端进行通信。
摘要由CSDN通过智能技术生成

前言:
平时,我们玩手机的时候,点击按钮,肉眼可见页面发生了变化。不要小看这小小的变化,底层通过了多层的网络传输(具体需要学习计算机网络),本篇将通过TCP(传输层)/IP(网络层),调用Socket(会话层)实现通信。

⭐注意事项

  1. sleep不能在主线程(UI线程),要另起一个线程
  2. 网络访问不能在主线程(UI线程),要另起一个线程
  3. 修改控件必须要在主线程(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
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值