很多人會比較推薦用AsyncTask來寫,可能是因為寫法比較簡單,不用透過Handler來處理,這邊就先簡單寫一個Send的功能就好了,Receive部分之後再寫。
受限於Android的網路開發規定,一開始還是必須要先在AndroidManifest.xml裡面加入這兩行:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
然後加入一個新的class來處理send socket的工作
UDP_Client.java
package com.example.chris.udp_asynctask; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.UnknownHostException; import android.annotation.SuppressLint; import android.os.AsyncTask; import android.os.Build; import android.util.Log; public class UDP_Client extends AsyncTask{ @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(String... params) { String str = params[0]; DatagramSocket ds = null; try { ds = new DatagramSocket(); InetAddress sendAddress = InetAddress.getByName(MainActivity.IPAddress); DatagramPacket dp; dp = new DatagramPacket(str.getBytes(), str.length(), sendAddress, MainActivity.ServerPort); ds.send(dp); } catch (Exception e) { e.printStackTrace(); } return null; } protected void onPostExecute(Void result) { super.onPostExecute(result); } }
可以發現用AsyncTask的方法架構跟Thread完全不同,就連可以帶入的參數設定上也不太一樣。
接著在MainActivity就可以直接呼叫execute()就搞定了,程式碼如下:
MainActivity.java
package com.example.chris.udp_asynctask; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.net.InetAddress; import java.net.UnknownHostException; public class MainActivity extends AppCompatActivity { public static int ServerPort = 8008; public static String IPAddress, mySocket; private TextView txv; private Button button01; private EditText edt_ip, edt_socket; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txv = (TextView)findViewById(R.id.textView3); edt_ip = (EditText)findViewById(R.id.editText); edt_socket = (EditText)findViewById(R.id.editText2); button01 = (Button)findViewById(R.id.button); button01.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { IPAddress = edt_ip.getText().toString(); // get ip address mySocket = edt_socket.getText().toString(); // get socket data // send socket data new UDP_Client().execute(mySocket); txv.setText("Send "+ mySocket + " to " + IPAddress); } }); } }
最後是layout的部分:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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.example.chris.udp_asynctask.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="172.20.10.2"
android:ems="10"
android:id="@+id/editText"
android:layout_alignBaseline="@+id/textView"
android:layout_alignBottom="@+id/textView"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="test"
android:ems="10"
android:id="@+id/editText2"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_toRightOf="@+id/textView2"
android:layout_toEndOf="@+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show message "
android:id="@+id/textView3"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp" />
<Button
android:text="Send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IP: "
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Socket: "
android:id="@+id/textView2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp" />
</RelativeLayout>
沒有留言:
張貼留言