【问题标题】:How Can I Track a person using its location in Android如何在 Android 中使用其位置跟踪一个人
【发布时间】:2016-04-16 04:54:36
【问题描述】:

我正在做一个项目...我需要使用其地理位置(纬度,经度)跟踪一个人.. 场景: - 当位置发生变化时,人员 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();
        }
    }
}

我正在使用一个函数连续调用这个类

【问题讨论】:

    标签: android mysql google-maps geolocation


    【解决方案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>
    

    【讨论】:

    • 你帮了我很多..非常感谢你......这意味着我需要将我在 doInBackground() 函数中的代码粘贴到 MyTask 类中的 doInBackground() 函数中......我ryt ?
    • 尝试创建关于如何管理警报管理器的新问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    相关资源
    最近更新 更多