Send data from Service to Fragment, Android

2020-03-06 08:09发布

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 my simple Service

public class ChallengeService extends Service {
    final String LOG_TAG = "myLogs";
    private String url = "";
    public static ArrayList<Exercises> exercises = new ArrayList<>();

    public void onCreate() {
        super.onCreate();
        Log.d(LOG_TAG, "onCreate");
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(LOG_TAG, "onStartCommand");
        url = intent.getStringExtra("Challenge_URL");
        new getChallenge(url).execute();
        return super.onStartCommand(intent, flags, startId);
    }

    public void onDestroy() {
        super.onDestroy();
        Log.d(LOG_TAG, "onDestroy");
    }

    public IBinder onBind(Intent intent) {
        Log.d(LOG_TAG, "onBind");
        return null;
    }

    public class getChallenge extends AsyncTask<Void,Void,String> {

        String mUrl;
        OkHttpClient client = new OkHttpClient();
        String result = "";

        public getChallenge(String url) {
            this.mUrl = url;
        }

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        @Override
        protected String doInBackground(Void... params) {
            Log.d("Background", "inBackground");
            try {
                URL mUrl = new URL(url);
                Log.d("URL!!!!", "url = " + url);
                urlConnection = (HttpURLConnection) mUrl.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                result = buffer.toString();

            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

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

And I need send list of exercises to my Fragment, how can I make it? I'm new with Services, and I haven't any idea, please help me

2条回答
女痞
2楼-- · 2020-03-06 08:34

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

查看更多
唯我独甜
3楼-- · 2020-03-06 08:40

You can do it by 2 methods.

  1. Save data to database and get data in fragment.
  2. Use Broadcast
查看更多
登录 后发表回答