我正在开展一个项目...我需要使用其地理位置(纬度,经度)跟踪一个人。 的情景: - 当位置变更时,人员A的位置正在MYSQL DB中的服务器上更新。 - B人需要通过他/她自己的设备(Android手机)在Google地图上查看人A
问题
当我建立与服务器的连接并尝试从MYSQL DB获取位置时...连接被破坏并且应用程序崩溃。 注意 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 :(得分: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>