2016-04-16 21 views
0
它的位置

我工作的一個項目...我需要使用它的地理位置(經度,緯度)來跟蹤我一個人跟蹤一個人.. 情景: - 人A的當位置變爲變化時,位置正在MYSQL數據庫中的服務器上更新。 - 某乙需要看到在谷歌地圖的人從A到他/她自己的設備(Android手機)如何可以使用Android的

問題

當我建立連接到服務器,並嘗試從MySQL數據庫獲取位置...連接被擊中,App崩潰。 注意 人B需要跟蹤,直到它到達特定點。 有沒有其他方法可以做到這一點? 感謝您提前幫助

下載跟蹤位置從服務器

private class downloadTrackingLocationsAsync extends AsyncTask<String, Void, String> { 
    @Override 
    protected void onPreExecute() { 
    } 
    @Override 
    protected String doInBackground(String... params) { 
     String ID = params[1]; 
     HttpURLConnection conn = null; 

     try { 
      // create connection 
      URL wsURL=new URL(params[0]); 
      conn=(HttpURLConnection) wsURL.openConnection(); 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
      conn.setUseCaches(false); 

      Uri.Builder builder = new Uri.Builder().appendQueryParameter("id", ID); 
      String data = builder.build().getEncodedQuery(); 
      byte[] outputInBytes = data.getBytes("UTF-8"); 
      conn.setRequestProperty("Content-Length", "" + Integer.toString(outputInBytes.length)); 
      conn.setDoOutput(true); 
      conn.setDoInput(true); 
      OutputStream os = conn.getOutputStream(); 
      os.write(outputInBytes); 
      os.close(); 

      //get data 
      InputStream bufferedInputStream = new BufferedInputStream(conn.getInputStream()); 
      // converting InputStream into String 
      Scanner scanner = new Scanner(bufferedInputStream); 
      String strJSON = scanner.useDelimiter("\\A").next(); 
      scanner.close(); 
      bufferedInputStream.close(); 
      return strJSON; 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); // URL is invalid 
     } catch (SocketTimeoutException e) { 
      e.printStackTrace(); // data retrieval or connection timed out 
     } catch (IOException e) { 
      e.printStackTrace(); // could not read response body 
      // (could not create input stream) 
     } finally { 
      if (conn != null) {conn.disconnect(); } 
     } 
     return null; 
    } 
    @Override 
    protected void onPostExecute(String result) { 
     if(result !=null) { 
      try { 
       JSONObject rootObject = new JSONObject(result); 

        double latitude = rootObject.optDouble("lattitude"); 
        double longitude = rootObject.optDouble("longitude"); 

        LatLng currentLocation = new LatLng(latitude, longitude); 
        PersonB_FragmentMap.updateTrackingLocation(currentLocation); 
       Log.i("Location", currentLocation.toString()); 
        Toast.makeText(context, "Tracking Location Downloaded", Toast.LENGTH_LONG).show(); 

      }catch (JSONException e){ 
       e.printStackTrace(); 
      } 
     } 
     else { 
      Toast.makeText(context, "Result Null", Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 

我使用的是功能不斷

+0

發佈您的代碼以獲得更好的解決方案 – Rgv

+0

我發佈了..看一看 –

回答

1

您應該使用AlarmManager服務調用這個類和在後臺做。 有關AlarmManager的更多詳細信息refer this link

使用AlarmManager,BroadcastReceiver,Service和Notification Manager在後臺進程中定期更新服務器的數據。

首先激活AlarmManager。在Activity類中編寫以下代碼

public class MainActivity extends ListActivity { 

    private static final long REPEAT_TIME = 1000 * 30; 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 
      setRecurringAlarm(this); 
     } 

     private void setRecurringAlarm(Context context) { 

      Calendar updateTime = Calendar.getInstance(); 
      updateTime.setTimeZone(TimeZone.getDefault()); 
      updateTime.set(Calendar.HOUR_OF_DAY, 12); 
      updateTime.set(Calendar.MINUTE, 30); 
      Intent downloader = new Intent(context, MyStartServiceReceiver.class); 
      downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

      PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, downloader,  PendingIntent.FLAG_CANCEL_CURRENT); 

      AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 

      alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent); 

      Log.d("MyActivity", "Set alarmManager.setRepeating to: " + updateTime.getTime().toLocaleString()); 

     } 

} 


First create BroadcastReceiver Class 
public class MyStartServiceReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
      Intent dailyUpdater = new Intent(context, MyService.class); 
      context.startService(dailyUpdater); 
      Log.d("AlarmReceiver", "Called context.startService from AlarmReceiver.onReceive"); 
    } 
} 

當應用程序關閉或處於後臺時,定期從服務器獲取數據並在狀態欄上顯示通知。

創建服務

public class MyService extends IntentService { 
    public MyService() { 
     super("MyServiceName"); 
    } 
    @Override 
    protected void onHandleIntent(Intent intent) { 
     Log.d("MyService", "About to execute MyTask"); 
     new MyTask().execute(); 
     this.sendNotification(this); 
    } 
    private class MyTask extends AsyncTask<String, Void, Boolean> { 
     @Override 
     protected Boolean doInBackground(String... strings) { 
       Log.d("MyService - MyTask", "Calling doInBackground within MyTask"); 
       return false; 
     } 
}   
private void sendNotification(Context context) { 
     Intent notificationIntent = new Intent(context, MainActivity.class); 
     PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); 
     NotificationManager notificationMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
     Notification notification = new Notification(android.R.drawable.star_on, "Refresh", System.currentTimeMillis()); 
     notification.flags |= Notification.FLAG_AUTO_CANCEL; 
     notification.setLatestEventInfo(context, "Title","Content", contentIntent); 
     notificationMgr.notify(0, notification); 
    } 
} 

不要忘記下面寫在AndroidManifest.xml行文件

<service android:name="MyService" ></service> 
<receiver android:name="MyStartServiceReceiver" ></receiver> 
+0

感謝您的考慮......我的行爲與此相同......您不明白....我認爲我的說法模糊不清...讓我清除... **問題是我無法從服務器上的人B的一方獲得位置,由於建立HTTP連接一次又一次它成爲崩潰**我認爲現在你更清晰... –

+0

你是從json格式的服務器獲取數據嗎? –

+0

是的,我....讓我分享下載代碼...看到我編輯過的文章中的代碼。 –

0

我覺得你應該先嚐試一些你自己問你遇到任何questions.If前一個問題,那麼每個人都應該回答這個問題。

+0

兄弟我試過這個....然後我要求另一個解決方案......你可以閱讀郵政再次......和問題陳述 –

相關問題