我如何在服务中获取经度和纬度并将其传递给主要活动的android studio

问题描述 投票:0回答:1

是否有一种方法可以获取服务中的纬度和经度,然后将其传递给主要活动?

java android android-studio
1个回答
0
投票

在使用中:

private static void sendMessageToActivity(Location location, String msg) {
    Intent intent = new Intent("GPSLocation");
    // You can also include some extra data.
    intent.putExtra("Status", msg);
    Bundle b = new Bundle();
    b.putParcelable("Location", location);
    intent.putExtra("Location", b);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

活动中:

注册接收者:

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
            mMessageReceiver, new IntentFilter("GPSLocation"));

并且在活动中使用此:

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get extra data included in the Intent
            String message = intent.getStringExtra("Status");
            Bundle b = intent.getBundleExtra("Location");
            lastKnownLoc = (Location) b.getParcelable("Location");
            if (lastKnownLoc != null) {
                tvLatitude.setText(String.valueOf(lastKnownLoc.getLatitude()));
                tvLongitude
                        .setText(String.valueOf(lastKnownLoc.getLongitude()));
                tvAccuracy.setText(String.valueOf(lastKnownLoc.getAccuracy()));
                tvTimestamp.setText((new Date(lastKnownLoc.getTime())
                        .toString()));
                tvProvider.setText(lastKnownLoc.getProvider());
            }
            tvStatus.setText(message);
            // Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        }
    };
热门问题
推荐问题
最新问题