Advertisement
vietanhlehuu

new TCP

Oct 25th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.31 KB | None | 0 0
  1. package testing.gps_location;
  2.  
  3. import android.Manifest;
  4. import android.content.Intent;
  5. import android.content.pm.PackageManager;
  6. import android.location.Location;
  7. import android.location.LocationListener;
  8. import android.location.LocationManager;
  9. import android.os.AsyncTask;
  10. import android.os.Build;
  11. import android.os.Bundle;
  12. import android.os.SystemClock;
  13. import android.provider.AlarmClock;
  14. import android.provider.Settings;
  15. import android.support.annotation.NonNull;
  16. import android.support.annotation.Nullable;
  17. import android.support.v4.app.ActivityCompat;
  18. import android.support.v7.app.AppCompatActivity;
  19. import android.util.Log;
  20. import android.view.View;
  21. import android.widget.Button;
  22. import android.widget.TextView;
  23.  
  24. import java.io.BufferedReader;
  25. import java.io.DataInputStream;
  26. import java.io.IOException;
  27. import java.io.InputStreamReader;
  28. import java.net.DatagramPacket;
  29. import java.net.DatagramSocket;
  30. import java.net.InetAddress;
  31. import java.net.NetworkInterface;
  32. import java.net.Socket;
  33. import java.net.SocketException;
  34. import java.net.UnknownHostException;
  35. import java.nio.channels.DatagramChannel;
  36. import java.util.Date;
  37. import java.util.Enumeration;
  38. import java.util.logging.Handler;
  39. import java.util.logging.LogRecord;
  40.  
  41. public class MainActivity extends AppCompatActivity {
  42.  
  43. private Button b;
  44. private TextView t;
  45. private LocationManager locationManager;
  46. private LocationListener listener;
  47. TextView textResponse = null;
  48.  
  49. @Override
  50. protected void onCreate(@Nullable Bundle savedInstanceState) {
  51. super.onCreate(savedInstanceState);
  52.  
  53. setContentView(R.layout.activity_main);
  54.  
  55. t = (TextView) findViewById(R.id.textView);
  56. b = (Button) findViewById(R.id.button);
  57. textResponse = t;
  58.  
  59. locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
  60. listener = new LocationListener() {
  61. @Override
  62. public void onLocationChanged(Location location) {
  63. t.append("\n " + location.getLongitude() + " " + location.getLatitude());
  64. MyUDP myUdp = new MyUDP("192.168.52.1",10000,location.getLongitude(),location.getLatitude());
  65. myUdp.execute();
  66.  
  67. }
  68.  
  69. @Override
  70. public void onStatusChanged(String s, int i, Bundle bundle) {
  71.  
  72. }
  73.  
  74. @Override
  75. public void onProviderEnabled(String s) {
  76.  
  77. }
  78.  
  79. @Override
  80. public void onProviderDisabled(String s) {
  81.  
  82. Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  83. startActivity(i);
  84. }
  85. };
  86.  
  87. configure_button();
  88. //sendDataUDP("192.168.56.1",10000);
  89.  
  90. //receiveDataTCP(5000,"192.168.56.1",t);
  91. MyTCP myClientTask = new MyTCP("192.168.56.1", 5000);
  92. myClientTask.execute();
  93. }
  94.  
  95. @Override
  96. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  97. switch (requestCode) {
  98. case 10:
  99. configure_button();
  100. break;
  101. default:
  102. break;
  103. }
  104. }
  105.  
  106. void configure_button() {
  107. // first check for permissions
  108. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  109. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  110. requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
  111. , 10);
  112. }
  113. return;
  114. }
  115. // this code won't execute IF permissions are not allowed, because in the line above there is return statement.
  116. b.setOnClickListener(new View.OnClickListener() {
  117. @Override
  118. public void onClick(View view) {
  119. //noinspection MissingPermission
  120. locationManager.requestLocationUpdates("gps", 5000, 0, listener);
  121. }
  122. });
  123. }
  124.  
  125. void sendDataUDP(String ipServer, int port, final String massage){
  126. final String finalIpServer = ipServer;
  127. final int SERVER_PORT = port;
  128. new Thread(new Runnable(){
  129. // private final String SERVER_ADDRESS = ipServer;//public ip of my server
  130.  
  131. @Override
  132. public void run() {
  133. try {
  134. //Preparing the socket
  135. InetAddress serverAddr = InetAddress.getByName(finalIpServer);
  136. DatagramSocket socket = new DatagramSocket();
  137. //Preparing the packet
  138. byte[] buf = massage.getBytes();
  139. DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, SERVER_PORT);
  140.  
  141. //Sending the packet
  142. Log.d("UDP", String.format("Sending: '%s' to %s:%s", new String(buf), finalIpServer, SERVER_PORT));
  143. socket.send(packet);
  144. Log.d("UDP", "Packet sent.");
  145. } catch (Exception e) {
  146. Log.e("UDP", "Client error", e);
  147. }
  148. }
  149. }).start();
  150. }
  151. void receiveDataTCP(int port, final String ipServer,final TextView textView){
  152. //t.append("\n Da vo roi nhe");
  153. final int Port = port;
  154. final String IpServer = ipServer;
  155.  
  156. new Thread(new Runnable() {
  157. @Override
  158. public void run() {
  159. while(true) {
  160. try {
  161. t.append("\n Da vo roi nhe");
  162.  
  163. Socket theSocket = new Socket(ipServer, Port);
  164. // textView.append("\n" +"Connected to "
  165. // + theSocket.getInetAddress() +" on port "
  166. // + theSocket.getPort() + " from port "
  167. // + theSocket.getLocalPort() + " of "
  168. // + theSocket.getLocalAddress());
  169. BufferedReader buff = new BufferedReader(new
  170. InputStreamReader(theSocket.getInputStream()));
  171. String inputLine;
  172. while ((inputLine = buff.readLine()) != null) {
  173.  
  174. textView.append("\n" + inputLine);
  175. }
  176.  
  177. theSocket.close();
  178. Thread.sleep(10000);
  179.  
  180.  
  181. } catch (UnknownHostException e) {
  182.  
  183. textView.append("\n" + e.toString());
  184. } catch (SocketException e) {
  185. textView.append("\n" + e.toString());
  186. } catch (IOException e) {
  187. textView.append("\n" + e.toString());
  188. } catch (Exception e) {
  189. textView.append("\n" + e.toString());
  190. }
  191. }
  192. }
  193. }
  194. ).start();
  195.  
  196. }
  197.  
  198. public class MyUDP extends AsyncTask <Void , Void , Void> {
  199. String dstAddress;
  200. int dstPort;
  201. String message;
  202. MyUDP(String addr, int port, double x,double y ) {
  203. dstAddress = addr;
  204. dstPort = port;
  205. message = x + "@" + y ;
  206. }
  207. @Override
  208. protected Void doInBackground(Void... arg0) {
  209. sendDataUDP(dstAddress,dstPort,message);
  210. return null;
  211. }
  212. @Override
  213. protected void onPostExecute(Void result) {
  214. super.onPostExecute(result);
  215. //textResponse.append("\n" + response);
  216. }
  217.  
  218.  
  219. }
  220. public class MyTCP extends AsyncTask<Void, String, Void> {
  221.  
  222. String dstAddress;
  223. int dstPort;
  224. String response = "";
  225.  
  226. MyTCP(String addr, int port) {
  227. dstAddress = addr;
  228. dstPort = port;
  229. }
  230.  
  231. @Override
  232. protected Void doInBackground(Void... arg0) {
  233.  
  234. Socket socket = null;
  235. //DataInputStream dataInputStream = null;
  236. while(true) {
  237. try {
  238. socket = new Socket(dstAddress, dstPort);
  239. //dataInputStream = new DataInputStream(socket.getInputStream());
  240. BufferedReader buff = new BufferedReader(new
  241. InputStreamReader(socket.getInputStream()));
  242. String inputLine= buff.readLine();
  243. while(inputLine != null) {
  244. //khi gọi hàm này thì onProgressUpdate sẽ thực thi
  245. publishProgress(inputLine);
  246. inputLine= buff.readLine();
  247.  
  248. }
  249. } catch (UnknownHostException e) {
  250. e.printStackTrace();
  251. response = "UnknownHostException: " + e.toString();
  252. } catch (IOException e) {
  253. e.printStackTrace();
  254. response = "IOException: " + e.toString();
  255. } finally {
  256. if (socket != null) {
  257. try {
  258. socket.close();
  259. } catch (IOException e) {
  260. e.printStackTrace();
  261. }
  262. }
  263.  
  264. }
  265. SystemClock.sleep(5000);
  266. }
  267.  
  268. //return ;
  269. }
  270. @Override
  271. protected void onProgressUpdate(String... values) {
  272. // TODO Auto-generated method stub
  273. super.onProgressUpdate(values);
  274. textResponse.append("\n" + values[0]);
  275. if(response != "") {
  276. textResponse.setText(response);
  277. response ="";
  278. }
  279. }
  280. @Override
  281. protected void onPostExecute(Void result) {
  282. super.onPostExecute(result);
  283. //textResponse.append("\n" + response);
  284. }
  285.  
  286. }
  287. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement