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
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 thisHowever, 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 fragmentThen in your Fragment you create a receiver
and register it in your
onResume
You also need to unregister it in your onPause using
getActivity().unregisterReceiver(receiver);
You can also read more about it here if interested
You can do it by 2 methods.