Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package testing.gps_location;
- import android.Manifest;
- import android.content.Intent;
- import android.content.pm.PackageManager;
- import android.location.Location;
- import android.location.LocationListener;
- import android.location.LocationManager;
- import android.os.AsyncTask;
- import android.os.Build;
- import android.os.Bundle;
- import android.os.SystemClock;
- import android.provider.AlarmClock;
- import android.provider.Settings;
- import android.support.annotation.NonNull;
- import android.support.annotation.Nullable;
- import android.support.v4.app.ActivityCompat;
- import android.support.v7.app.AppCompatActivity;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import java.io.BufferedReader;
- import java.io.DataInputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.NetworkInterface;
- import java.net.Socket;
- import java.net.SocketException;
- import java.net.UnknownHostException;
- import java.nio.channels.DatagramChannel;
- import java.util.Date;
- import java.util.Enumeration;
- import java.util.logging.Handler;
- import java.util.logging.LogRecord;
- public class MainActivity extends AppCompatActivity {
- private Button b;
- private TextView t;
- private LocationManager locationManager;
- private LocationListener listener;
- TextView textResponse = null;
- @Override
- protected void onCreate(@Nullable Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- t = (TextView) findViewById(R.id.textView);
- b = (Button) findViewById(R.id.button);
- textResponse = t;
- locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
- listener = new LocationListener() {
- @Override
- public void onLocationChanged(Location location) {
- t.append("\n " + location.getLongitude() + " " + location.getLatitude());
- MyUDP myUdp = new MyUDP("192.168.52.1",10000,location.getLongitude(),location.getLatitude());
- myUdp.execute();
- }
- @Override
- public void onStatusChanged(String s, int i, Bundle bundle) {
- }
- @Override
- public void onProviderEnabled(String s) {
- }
- @Override
- public void onProviderDisabled(String s) {
- Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
- startActivity(i);
- }
- };
- configure_button();
- //sendDataUDP("192.168.56.1",10000);
- //receiveDataTCP(5000,"192.168.56.1",t);
- MyTCP myClientTask = new MyTCP("192.168.56.1", 5000);
- myClientTask.execute();
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- switch (requestCode) {
- case 10:
- configure_button();
- break;
- default:
- break;
- }
- }
- void configure_button() {
- // first check for permissions
- if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
- , 10);
- }
- return;
- }
- // this code won't execute IF permissions are not allowed, because in the line above there is return statement.
- b.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- //noinspection MissingPermission
- locationManager.requestLocationUpdates("gps", 5000, 0, listener);
- }
- });
- }
- void sendDataUDP(String ipServer, int port, final String massage){
- final String finalIpServer = ipServer;
- final int SERVER_PORT = port;
- new Thread(new Runnable(){
- // private final String SERVER_ADDRESS = ipServer;//public ip of my server
- @Override
- public void run() {
- try {
- //Preparing the socket
- InetAddress serverAddr = InetAddress.getByName(finalIpServer);
- DatagramSocket socket = new DatagramSocket();
- //Preparing the packet
- byte[] buf = massage.getBytes();
- DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, SERVER_PORT);
- //Sending the packet
- Log.d("UDP", String.format("Sending: '%s' to %s:%s", new String(buf), finalIpServer, SERVER_PORT));
- socket.send(packet);
- Log.d("UDP", "Packet sent.");
- } catch (Exception e) {
- Log.e("UDP", "Client error", e);
- }
- }
- }).start();
- }
- void receiveDataTCP(int port, final String ipServer,final TextView textView){
- //t.append("\n Da vo roi nhe");
- final int Port = port;
- final String IpServer = ipServer;
- new Thread(new Runnable() {
- @Override
- public void run() {
- while(true) {
- try {
- t.append("\n Da vo roi nhe");
- Socket theSocket = new Socket(ipServer, Port);
- // textView.append("\n" +"Connected to "
- // + theSocket.getInetAddress() +" on port "
- // + theSocket.getPort() + " from port "
- // + theSocket.getLocalPort() + " of "
- // + theSocket.getLocalAddress());
- BufferedReader buff = new BufferedReader(new
- InputStreamReader(theSocket.getInputStream()));
- String inputLine;
- while ((inputLine = buff.readLine()) != null) {
- textView.append("\n" + inputLine);
- }
- theSocket.close();
- Thread.sleep(10000);
- } catch (UnknownHostException e) {
- textView.append("\n" + e.toString());
- } catch (SocketException e) {
- textView.append("\n" + e.toString());
- } catch (IOException e) {
- textView.append("\n" + e.toString());
- } catch (Exception e) {
- textView.append("\n" + e.toString());
- }
- }
- }
- }
- ).start();
- }
- public class MyUDP extends AsyncTask <Void , Void , Void> {
- String dstAddress;
- int dstPort;
- String message;
- MyUDP(String addr, int port, double x,double y ) {
- dstAddress = addr;
- dstPort = port;
- message = x + "@" + y ;
- }
- @Override
- protected Void doInBackground(Void... arg0) {
- sendDataUDP(dstAddress,dstPort,message);
- return null;
- }
- @Override
- protected void onPostExecute(Void result) {
- super.onPostExecute(result);
- //textResponse.append("\n" + response);
- }
- }
- public class MyTCP extends AsyncTask<Void, String, Void> {
- String dstAddress;
- int dstPort;
- String response = "";
- MyTCP(String addr, int port) {
- dstAddress = addr;
- dstPort = port;
- }
- @Override
- protected Void doInBackground(Void... arg0) {
- Socket socket = null;
- //DataInputStream dataInputStream = null;
- while(true) {
- try {
- socket = new Socket(dstAddress, dstPort);
- //dataInputStream = new DataInputStream(socket.getInputStream());
- BufferedReader buff = new BufferedReader(new
- InputStreamReader(socket.getInputStream()));
- String inputLine= buff.readLine();
- while(inputLine != null) {
- //khi gọi hàm này thì onProgressUpdate sẽ thực thi
- publishProgress(inputLine);
- inputLine= buff.readLine();
- }
- } catch (UnknownHostException e) {
- e.printStackTrace();
- response = "UnknownHostException: " + e.toString();
- } catch (IOException e) {
- e.printStackTrace();
- response = "IOException: " + e.toString();
- } finally {
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- SystemClock.sleep(5000);
- }
- //return ;
- }
- @Override
- protected void onProgressUpdate(String... values) {
- // TODO Auto-generated method stub
- super.onProgressUpdate(values);
- textResponse.append("\n" + values[0]);
- if(response != "") {
- textResponse.setText(response);
- response ="";
- }
- }
- @Override
- protected void onPostExecute(Void result) {
- super.onPostExecute(result);
- //textResponse.append("\n" + response);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement