在android中定期发送当前位置到服务器

发布于 2025-01-08 02:14:59 字数 97 浏览 1 评论 0原文

我必须定期向服务器发送当前位置详细信息(纬度和经度)(例如:每 5 分钟一次)。有什么最好的办法吗?我知道如何获取当前位置和位置如何将详细信息发送到服务器。但如何定期重复此操作呢?

I have to send my current location details (lat & long) to server periodically (Ex: for every 5 minutes). Is there any best way? I know how to get the current location & how to send the details to server. But how do I repeat this in periodic intervals?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一场信仰旅途 2025-01-15 02:14:59

使用 AlarmManager 注册一个闹钟,以便在用户第一次打开应用程序时 5 分钟后唤醒。创建一个服务(获取位置并更新到服务器)以在警报通知您的应用程序时运行。服务完成工作后,5分钟后再次注册闹钟唤醒。通过这种方式你可以完成你的任务。

ref

Android:如何定期向服务器发送位置

http://developer.android.com/reference/android/app/AlarmManager.html

http://developer.android.com/reference/android/app/Service.html

第一次编辑 - 添加代码示例

第 1 步 - 创建警报管理器并注册警报

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

Intent intent = new Intent(Main.this, YourWakefulReceiver.class);
bool flag = (PendingIntent.getBroadcast(Main.this, 0,
                intent, PendingIntent.FLAG_NO_CREATE)==null);
/*Register alarm if not registered already*/
if(flag){
PendingIntent alarmIntent = PendingIntent.getBroadcast(Main.this, 0,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Create Calendar obj called calendar
        Calendar calendar = Calendar.getInstance();

/* Setting alarm for every one hour from the current time.*/
int intervalTimeMillis = 1000 * 60 * 60; // 1 hour 
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), intervalTimeMillis,
                        alarmIntent);
}

第 2 步 - 创建接收器类

public class YourWakefulReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
            Intent service = new Intent(context, SimpleWakefulService.class);
            startWakefulService(context, service);
        }
    }
}

Setp 3 - 创建Service类

public class SimpleWakefulService extends IntentService {

    private static String tagName = "YourService";

    public SimpleWakefulService() {
        super("YourService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // Start your location
        LocationUtil.startLocationListener();
        try {
        // Wait for 10 seconds
            Thread.sleep(1000*10);
        } catch (InterruptedException e) {
        }
        //Stop location listener
        LocationUtil.stopLocationListener();
        // upload or save location
        uploadGps();

        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }

}

步骤4 - 注册服务和接收者

<service android:name="com.envision.ghari.services.SimpleWakefulService"></service>
        <receiver android:name="com.envision.ghari.receivers.YourWakefulReceiver"></receiver>

注意:这段代码是为了理解实现。它不会编译。

Register an alarm using AlarmManager to wake up after 5min when user open the application first time. create a service(fetch location and update to server) to run when alarm notifies your application. After the service finished the work , register for an alarm again to wake up after 5min. by this way you can achieve your task.

ref

Android: How to periodically send location to a server

http://developer.android.com/reference/android/app/AlarmManager.html

http://developer.android.com/reference/android/app/Service.html

1st Edit - Adding code sample

Step 1 - Create alarm manager and register alarm

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

Intent intent = new Intent(Main.this, YourWakefulReceiver.class);
bool flag = (PendingIntent.getBroadcast(Main.this, 0,
                intent, PendingIntent.FLAG_NO_CREATE)==null);
/*Register alarm if not registered already*/
if(flag){
PendingIntent alarmIntent = PendingIntent.getBroadcast(Main.this, 0,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Create Calendar obj called calendar
        Calendar calendar = Calendar.getInstance();

/* Setting alarm for every one hour from the current time.*/
int intervalTimeMillis = 1000 * 60 * 60; // 1 hour 
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), intervalTimeMillis,
                        alarmIntent);
}

Step 2 - Create Receiver class

public class YourWakefulReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
            Intent service = new Intent(context, SimpleWakefulService.class);
            startWakefulService(context, service);
        }
    }
}

Setp 3 - Create Service class

public class SimpleWakefulService extends IntentService {

    private static String tagName = "YourService";

    public SimpleWakefulService() {
        super("YourService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // Start your location
        LocationUtil.startLocationListener();
        try {
        // Wait for 10 seconds
            Thread.sleep(1000*10);
        } catch (InterruptedException e) {
        }
        //Stop location listener
        LocationUtil.stopLocationListener();
        // upload or save location
        uploadGps();

        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }

}

Step 4 - Register service and receiver

<service android:name="com.envision.ghari.services.SimpleWakefulService"></service>
        <receiver android:name="com.envision.ghari.receivers.YourWakefulReceiver"></receiver>

Note : This code is to understand the implementation. It will not compile.

永不分离 2025-01-15 02:14:59

使用 BroadcastReceiver
是发送定期请求的不错选择。

这里是使用 BroadcastReceiver 的教程。

Using BroadcastReceiver
is a good choice for sending periodic requests.

Here is a tutorial to use BroadcastReceiver.

猥︴琐丶欲为 2025-01-15 02:14:59

使用 AlarmManager 唤醒服务并将您获得的位置发布到服务器的最佳方法。

Best way to wakeup the service using the AlarmManager and post the location you get to the server.

爱的那么颓废 2025-01-15 02:14:59

由于它不需要 UI 交互,因此您应该为此创建一个服务,服务将调用 requestLocationUpdates 方法,在此方法中,传递参数最短时间为 5 分钟。

As it does not require UI interaction you should create a service for this, service will invoke requestLocationUpdates method, in this method, pass parameter minimum time to 5 mins.

厌味 2025-01-15 02:14:59

我正在开发一个应用程序,可以在服务中全天 10 到 15 秒内获取手机的位置,它工作正常,但有时网络提供商侦听器的 OnLocationChanged 方法停止被调用。

 import android.location.Address;
    import android.location.Geocoder;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ListView;
    import android.widget.SimpleCursorAdapter;
    import android.widget.TextView;


    import java.io.IOException;
    import java.util.List;

    import foodinn.databases.LocationUpdaterDatabase;

    public class LocationUpdatesActivity extends AppCompatActivity {
        private LocationUpdaterDatabase locationUpdaterDatabase;

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

            locationUpdaterDatabase = new LocationUpdaterDatabase(this, "Locations.db", null, 1);

            final Geocoder geocoder = new Geocoder(this);

            ListView listView = (ListView) findViewById(R.id.locationUpdatesListView);

            listView.setAdapter(new SimpleCursorAdapter(this, R.layout.location_updates_list_view_view, locationUpdaterDatabase.getLocationUpdates(), new String[] {"latitude", "longitude", "whenUpdated"}, new int[] {R.id.listViewTextView1, R.id.listViewTextView2, R.id.listViewTextView3}, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER));

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    double latitude = Double.valueOf(((TextView) view.findViewById(R.id.listViewTextView1)).getText().toString());
                    double longitude = Double.valueOf(((TextView) view.findViewById(R.id.listViewTextView2)).getText().toString());

                    try {
                        List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);

                        String address = addressList.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                        String city = addressList.get(0).getLocality();
                        String state = addressList.get(0).getAdminArea();
                        String country = addressList.get(0).getCountryName();
                        String postalCode = addressList.get(0).getPostalCode();
                        String knownName = addressList.get(0).getFeatureName();

                        ((TextView) view.findViewById(R.id.listViewTextView4)).setText(address + ", " + city + ", " + country);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

I am developing an application that gets position of the cell phone all day long in 10 and 15 seconds in a service, it works fine but sometimes the method OnLocationChanged of the Network provider listener stop to being called.

 import android.location.Address;
    import android.location.Geocoder;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ListView;
    import android.widget.SimpleCursorAdapter;
    import android.widget.TextView;


    import java.io.IOException;
    import java.util.List;

    import foodinn.databases.LocationUpdaterDatabase;

    public class LocationUpdatesActivity extends AppCompatActivity {
        private LocationUpdaterDatabase locationUpdaterDatabase;

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

            locationUpdaterDatabase = new LocationUpdaterDatabase(this, "Locations.db", null, 1);

            final Geocoder geocoder = new Geocoder(this);

            ListView listView = (ListView) findViewById(R.id.locationUpdatesListView);

            listView.setAdapter(new SimpleCursorAdapter(this, R.layout.location_updates_list_view_view, locationUpdaterDatabase.getLocationUpdates(), new String[] {"latitude", "longitude", "whenUpdated"}, new int[] {R.id.listViewTextView1, R.id.listViewTextView2, R.id.listViewTextView3}, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER));

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    double latitude = Double.valueOf(((TextView) view.findViewById(R.id.listViewTextView1)).getText().toString());
                    double longitude = Double.valueOf(((TextView) view.findViewById(R.id.listViewTextView2)).getText().toString());

                    try {
                        List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);

                        String address = addressList.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                        String city = addressList.get(0).getLocality();
                        String state = addressList.get(0).getAdminArea();
                        String country = addressList.get(0).getCountryName();
                        String postalCode = addressList.get(0).getPostalCode();
                        String knownName = addressList.get(0).getFeatureName();

                        ((TextView) view.findViewById(R.id.listViewTextView4)).setText(address + ", " + city + ", " + country);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文