標籤:android gprs socket 傳輸
手機使用GPRS網路與伺服器進行Socket通訊,代碼:http://download.csdn.net/detail/wu20093346/7768481
用UDP協議與Socket調試工具進行測試。
SocketActivity.java:
package com.example.socket;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import android.os.Bundle;import android.app.Activity;import android.view.View;import android.widget.Button;import android.view.View.OnClickListener;public class SocketActivity extends Activity {private Button startButton = null;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_socket);startButton = (Button)findViewById(R.id.startListener);startButton.setOnClickListener(new StartSocketListener());}class StartSocketListener implements OnClickListener{@Overridepublic void onClick(View v){new ServerThread().start();}}class ServerThread extends Thread{public void run(){try{DatagramSocket socket = new DatagramSocket(1234);InetAddress serverAddress = InetAddress.getByName("115.238.249.92");String str = "hello";byte data[] = str.getBytes();DatagramPacket packet = new DatagramPacket(data,data.length,serverAddress,1234);socket.send(packet);}catch (Exception e){e.printStackTrace();}}}}activity_socket.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" tools:context=".SocketActivity" > <Button android:id="@+id/startListener" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:onClick="OnClickListener" android:text="@string/Start" /></RelativeLayout>
Socket調試工具建立UDP Server監聽1234連接埠,本機IP為115.238.249.92。安裝運行apk,按下Send按鈕,伺服器端收到資料。
注意在AndroidManifest.xml中添加:
<uses-permission android:name="android.permission.INTERNET" />