2017-07-03 28 views
0

我找到了關於gps位置服務的教程。 每件事情都很好。 我想寫的下一件事是傳遞座標形式的應用程序到MySQL。 我已經嘗試了幾個關於android mysql的教程,但我不知道如何將它們應用於此代碼。從android中插入座標到mysql

我想實現的是onLocationChanged向數據庫發送經緯度。

有人能告訴我如何做到這一點?

這是代碼:

connect.php

<?php 
define('HOST','localhost'); 
define('USER',''); 
define('PASS',''); 
define('DB','coordinates'); 

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect'); 
?> 

insert.php

<?php 
require_once('connect.php'); 

if($_SERVER['REQUEST_METHOD']=='POST'){ 
    $la = $_POST['la_string']; 
    $lo = $_POST['lo_string']; 

    $get_result = $con->query("INSERT INTO gps(la,lo) VALUES ('$la','$lo')"); 

    if($get_result === true){ 
    echo "Successfully Registered"; 
    }else{ 
    echo "Not Registered"; 
    } 
}else{ 
    echo 'error'; 
} 

>

MainActivity.java

public class MainActivity extends AppCompatActivity { 

private Button start, stop, exit; 
private TextView data_lo, text_lo, text_la, data_la; 
private BroadcastReceiver broadcastReceiver; 
private String la_string,lo_string; 





@Override 
protected void onResume() { 
    super.onResume(); 
    if (broadcastReceiver == null) { 
     broadcastReceiver = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 
       data_la.setText("" + intent.getExtras().get("latitude")); 
       data_lo.setText("" + intent.getExtras().get("longitude")); 

      } 
     }; 
    } 

    registerReceiver(broadcastReceiver, new IntentFilter("location_update")); 

} 




@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    if(broadcastReceiver != null){ 
     unregisterReceiver(broadcastReceiver); 
    } 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    start = (Button) findViewById(R.id.start); 
    stop = (Button) findViewById(R.id.stop); 
    data_la = (TextView) findViewById(R.id.data_la); 
    data_lo = (TextView) findViewById(R.id.data_lo); 
    text_la = (TextView) findViewById(R.id.text_la); 
    text_lo = (TextView) findViewById(R.id.text_lo); 
    exit = (Button) findViewById(R.id.exit); 



    if(!runtime_permissions()) 
     enable_buttons(); 

} 

private void enable_buttons() { 

    start.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent i =new Intent(getApplicationContext(),GPS_Service.class); 
      startService(i); 
     } 
    }); 

    stop.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) {Intent i = new Intent(getApplicationContext(),GPS_Service.class); 
      stopService(i); 

     } 
    }); 

} 

private boolean runtime_permissions() { 
    if(Build.VERSION.SDK_INT >= 23 && 
      ContextCompat.checkSelfPermission 
        (this, Manifest.permission.ACCESS_FINE_LOCATION) 
        != PackageManager.PERMISSION_GRANTED && 
      ContextCompat.checkSelfPermission 
        (this, Manifest.permission.ACCESS_COARSE_LOCATION) 
        != PackageManager.PERMISSION_GRANTED){ 
     requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, 
       Manifest.permission.ACCESS_COARSE_LOCATION},100); 

     return true; 
    } 
    return false; 
} 


@Override 
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
    if(requestCode == 100){ 
     if(grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){ 
      enable_buttons(); 
     }else { 
      runtime_permissions(); 
     } 
    } 
}} 

GPS_Service.java

public class GPS_Service extends Service { 


private LocationListener locationListener; 
private LocationManager locationManager; 


@Nullable 
@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public void onCreate() { 

    locationListener = new LocationListener() { 
     @Override 
     public void onLocationChanged(Location location) { 
      Intent i = new Intent("location_update"); 
      i.putExtra("latitude", location.getLatitude()); 
      i.putExtra("longitude", location.getLongitude()); 
      sendBroadcast(i); 




     } 






     @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); 
      i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
      startActivity(i); 
     } 
    }; 

    locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); 

    //noinspection MissingPermission 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,locationListener); 

} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    if(locationManager != null){ 
     //noinspection MissingPermission 
     locationManager.removeUpdates(locationListener); 
    } 
}} 

回答

0

你必須要通過HttpClient的一個電話到你的服務器,並通過爲郵寄您的數據與您的數據編碼。

try{ 
     String data = URLEncoder.encode("la_string", "UTF-8") + "=" + 
      URLEncoder.encode(data_la.text, "UTF-8"); 
     data += "&" + URLEncoder.encode("lo_string", "UTF-8") + "=" + 
      URLEncoder.encode(data_lo.text, "UTF-8"); 

     URL url = new URL(URL); 
     URLConnection conn = url.openConnection(); 

     conn.setDoOutput(true); 
     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 

     wr.write(data); 
     wr.flush(); 

     BufferedReader reader = new BufferedReader(new 
      InputStreamReader(conn.getInputStream())); 

     StringBuilder sb = new StringBuilder(); 
     String line = null; 

     // Read Server Response if you have something to do with it 
     while((line = reader.readLine()) != null) { 
      sb.append(line); 
      break; 
     } 

     return sb.toString(); 
    } catch(Exception e){ 
     return new String("Exception: " + e.getMessage()); 
    } 

這裏你可以看到一個完整的例子:https://www.tutorialspoint.com/android/android_php_mysql.htm

+0

我還是不明白,你在哪裏我已經把這段代碼。在MainActivity或GPS_Service –

+0

它取決於你想調用服務器來存儲值的時間 – fmaccaroni

+0

在應用程序中,我有兩個按鈕,啓動和停止。我點擊開始,等待座標。更新時間是每3秒鐘一次。 我想在每次更改位置時自動存儲值。 –