How to get data from service to activity

后端 未结 4 1924
-上瘾入骨i
-上瘾入骨i 2020-11-27 04:11

In my app I have an activity and a service... The service will broadcast messages gathered from data from GPS... The Activity should receive the broadcast messages and updat

4条回答
  •  眼角桃花
    2020-11-27 04:40

    In my Service class I wrote this

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

    and at the Activity side we have to receive this Broadcast message

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

    By this way you can send message to an Activity. here mMessageReceiver is the class in that class you will perform what ever you want....

    in my code I did this....

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

提交回复
热议问题