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

时间:2012-02-23 04:44:55

标签: android gps

我必须定期向服务器发送我当前的位置详细信息(lat& long)(例如:每5分钟一次)。有什么最好的方法吗?我知道如何获得当前位置&如何将详细信息发送到服务器。但是如何定期重复这个?

5 个答案:

答案 0 :(得分:10)

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

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

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

步骤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步 - 创建Receiver类

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 - 创建服务类

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>

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

答案 1 :(得分:2)

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

Here是使用BroadcastReceiver的教程。

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

我正在开发一个应用程序,它可以在服务中整天在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();
                    }
                }
            });
        }
    }