2012-02-23 23 views
9

Tôi phải gửi chi tiết vị trí hiện tại của mình (lat & long) đến máy chủ định kỳ (Ví dụ: cứ 5 phút một lần). Có cách nào tốt nhất không? Tôi biết cách lấy vị trí hiện tại & cách gửi chi tiết đến máy chủ. Nhưng làm thế nào để tôi lặp lại điều này trong khoảng thời gian định kỳ?Gửi Vị trí Hiện tại đến máy chủ định kỳ trong android

+1

Vui lòng kiểm tra điều này, nhiều ứng dụng tương tự và đang hoạt động tốt nhưng tôi cần một số trợ giúp về một số tính năng mà bạn sẽ biết sau khi đọc bài đăng và xin lỗi vì đã đặt câu trả lời này tùy chọn nhận xét. . http://stackoverflow.com/questions/14088095/how-can-i-send-the-gps-and-network-location-cordinates-to-a-server-static-ip/14103445#14103445 – user2010282

Trả lời

9

Đăng ký báo thức bằng cách sử dụng AlarmManager để đánh thức sau 5 phút khi người dùng mở ứng dụng lần đầu tiên. tạo một dịch vụ (tìm vị trí và cập nhật lên máy chủ) để chạy khi báo động thông báo cho ứng dụng của bạn. Sau khi dịch vụ kết thúc công việc, đăng ký báo thức lần nữa để thức dậy sau 5 phút. bằng cách này bạn có thể đạt được nhiệm vụ của mình.

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 - Thêm mẫu mã

Bước 1 - Tạo quản lý báo động và đăng ký báo

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 

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

Bước 2 - Tạo Receiver lớp

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 - Tạo lớp Service

public class YourService 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); 
    } 

} 

Bước 4 - Đăng ký dịch vụ và người nhận

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

Lưu ý: Mã này là hiểu việc triển khai. Nó sẽ không biên dịch.

+2

Tôi muốn điều này câu trả lời là một chút thịt hơn. –

+0

cũng thêm kiểm tra tính khả dụng của Mạng.Nếu mạng không khả dụng thì lưu trữ tọa độ cục bộ và gửi chúng đến máy chủ khi mạng có ở đó – Harsh

+0

có lẽ là cách tốt nhất để bắt đầu .. –

0

Vì không yêu cầu tương tác giao diện người dùng, bạn nên tạo dịch vụ cho dịch vụ này, dịch vụ sẽ gọi phương thức requestLocationUpdates, trong phương pháp này, chuyển thời gian tối thiểu tham số đến 5 phút.

1

Sử dụng BroadcastReceiver là lựa chọn tốt để gửi yêu cầu định kỳ.

Here là hướng dẫn sử dụng BroadcastReceiver.

1

Cách tốt nhất để đánh thức dịch vụ bằng cách sử dụng AlarmManager và đăng vị trí bạn đến máy chủ.

0

Tôi đang phát triển một ứng dụng nhận vị trí điện thoại di động cả ngày trong 10 và 15 giây trong một dịch vụ, nó hoạt động tốt nhưng đôi khi phương pháp OnLocationChanged của trình lắng nghe nhà cung cấp mạng ngừng được gọi.

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(); 
        } 
       } 
      }); 
     } 
    } 
+0

Trong khi đoạn mã này có thể giải quyết câu hỏi, [bao gồm giải thích] (http: //meta.stackexchange .com/questions/114762/giải thích-hoàn toàn-dựa trên-câu trả lời) thực sự giúp cải thiện chất lượng bài viết của bạn. Hãy nhớ rằng bạn đang trả lời câu hỏi cho người đọc trong tương lai và những người đó có thể không biết lý do cho đề xuất mã của bạn. –

Các vấn đề liên quan