【问题标题】:Android share location data between activitiesAndroid 在 Activity 之间共享位置数据
【发布时间】:2016-04-08 10:09:14
【问题描述】:

我有一个包含两个活动 A 和 B(谷歌地图)的应用程序,两者都需要定期接收 GPS 位置。我需要从活动 A 到 B 并返回应用程序继续检索 GPS 位置而不会中断。为了解决这个问题,我想到了两种方法:

第一种是使用在应用启动时启动的服务并不断检索 GPS 位置,并以某种方式通知两个活动有关新数据,然后,当应用完成时停止检索位置。

第二种方法是使用片段,我只有一个活动不断检索 GPS 位置,然后我有两个片段显示 A 和 B 内容并以某种方式使用从活动接收到的位置数据。

当我说“不知何故”时,我想说我不知道​​怎么做:-)

您对如何实施这两种方法有什么建议,或者您能提出更好的方法吗?

【问题讨论】:

    标签: android service background gps location


    【解决方案1】:

    #1 每当位置发生变化时,发送意图并在您想要的地方接收它

     LocalBroadcastManager mLocalBroadcastManager;
    
     @Override
     public void onLocationChanged(Location location) {
         Intent intent = new Intent();
         intent.putExtra("com.exmaple.sample", location);
         mLocalBroadcastManager.sendBroadcast(intent);
     }
    

    #2 每当位置改变时,发送意图并在你想要的地方接收它(与 1 相同)

    @Override
    public void onLocationChanged(Location location) {
        Intent intent = new Intent();
        intent.putExtra("com.exmaple.sample", location);
        sendBroadcast(intent);
    }
    

    #3 或者,只传递一次未决意图,然后接收位置

    Intent intent = new Intent(mContext, YourBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 1, intent, 0);
    
    mLocManager = (LocationManager)getSystemService(LOCATION_SERVICE);
    mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, pendingIntent);
    

    #4 创建一个静态变量,然后定期从活动中轮询它。请注意,您应该优化轮询频率,因为不能保证获得新的位置。这可能是不好的方法,但对于您的场景来说可能是值得的

    public static Location sLastLocation;
    
    @Override
    public void onLocationChanged(Location location) {
        sLastLocation = location;
    }
    

    #5 使用事件总线,link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      相关资源
      最近更新 更多