2012-03-25 65 views
0

我試圖設計一個近距離警報應用程序,在用戶進入學校區域並在進入時以超過特定速度行駛時通知警報。如何通過服務在Android中的活動中使用更改的數據?

我需要運行一個後臺服務來計算用戶位置和速度。

我需要一個活動來接收用戶不斷變化的緯度/經度和速度值,並使用這些值來計算當前位置和學校位置(從數據庫接收的座標之間的距離)併發出警報if該距離小於已設定的接近半徑。

回答

1

你有什麼問題? 我在我最後的一個項目中完成了這項工作。 您必須在您的服務中實施GPS偵聽器。 我爲你的服務和你的活動之間的溝通建議一個廣播。 如果你想要一個鬧鐘,如果你的活動是在視圖中,你必須在活動中實現你的鬧鐘。否則,您必須在您的服務中創建一個pendingIntent,並在其時間內發出通知。

可能的onCreate您的服務:

@Override 
public void onCreate() { 

    myNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    myServiceBroadcastReceiver = new MyServiceBroadcastReceiver(); 
    MyApplication.getAppContext().registerReceiver(myServiceBroadcastReceiver, new IntentFilter(MyApplication.APP_UPDATE_DEMAND)); 

    myNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 




    myLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

    myLocListener = new MyLocListener(); 


    myLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MyApplication.GPS_UPDATE_PERIOD, 0, myLocListener); 
    myLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MyApplication.NETWORK_UPDATE_PERIOD, 0, myLocListener); // comment this line out if you want only gps! 
} 

你的榜樣LocationListener的類

private class MyLocListener implements LocationListener { 

    public void onLocationChanged(Location location) { 

     String lat = Double.toString(location.getLatitude()); 
     String lng = Double.toString(location.getLongitude(); 
//evaluate lat and lng here, fire a notification or send a broadcast if the activity is in view. 

     } 
    } 

    public void onProviderDisabled(String provider) { 
    // Do something 

    } 

    public void onProviderEnabled(String provider) { 
    // Do something 

    } 

    public void onStatusChanged(String provider, int status, 
      Bundle extras) { 
    // Do something 
    } 
} 

如果你想評價緯度和經度的服務(活動不考慮),你可以這樣做onLocationChanged()如果你想評估你的活動中的GPS數據(在視圖中),你可以發送廣播到你的活動。 還有其他的可能性給活動提供數據,但對我來說,廣播解決​​方案是最好的選擇(也必須發送其他信息)。

相關問題