Send data from Service to Fragment, Android

前端 未结 2 1821
难免孤独
难免孤独 2021-01-07 03:15

Good evening!
I have small problem with Service. At first, I have fragment with several TextViews. Into these TextView I want put text from my Service. And this code of

相关标签:
2条回答
  • 2021-01-07 03:45

    You can do it by 2 methods.

    1. Save data to database and get data in fragment.
    2. Use Broadcast
    0 讨论(0)
  • 2021-01-07 04:02

    Simply broadcast the result from your service and receive it in your fragment through a Broadcast Receiver

    You could, for example, broadcast your exercises in the onPostExecute like this

        @Override
        protected void onPostExecute(String strJson) {
            super.onPostExecute(strJson);
            Log.d(LOG_TAG, strJson + " " + url);
            exercises = ParseJSON.ChallengeParseJSON(strJson);
            Log.d("Challenges", "challenges: " + exercises.get(0).getName() + " " + exercises.get(1).getName());
    
            Intent intent = new Intent(FILTER); //FILTER is a string to identify this intent
            intent.putExtra(MY_KEY, exercises); 
            sendBroadcast(intent);
        }
    

    However, Your Exercise object needs to be parcelable for this to work smoothly. Or you could just broadcast your raw json string and call your ParseJSON.ChallengeParseJSON(strJson); in your fragment

    Then in your Fragment you create a receiver

    private BroadcastReceiver receiver = new BroadcastReceiver() {
    
    @Override
    public void onReceive(Context context, Intent intent) {
      ArrayList<Exercises> exercises = intent.getExtras().get(MY_KEY);
    
      //or
      //exercises = ParseJSON.ChallengeParseJSON(intent.getStringExtra(MY_KEY));
    
       }
    };
    

    and register it in your onResume

      @Override
     protected void onResume() {
       super.onResume();
       getActivity().registerReceiver(receiver, new IntentFilter(FILTER));
     }
    

    You also need to unregister it in your onPause using getActivity().unregisterReceiver(receiver);

    You can also read more about it here if interested

    0 讨论(0)
提交回复
热议问题