Advertisement
tiberiugaspar

MyService

Dec 10th, 2019
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. import android.app.IntentService;
  2. import android.content.Intent;
  3. import android.support.annotation.Nullable;
  4. import android.support.v4.content.LocalBroadcastManager;
  5. import android.util.Log;
  6.  
  7. import java.io.BufferedReader;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.InputStreamReader;
  11. import java.net.MalformedURLException;
  12. import java.net.URL;
  13.  
  14. public class MyService extends IntentService {
  15.  
  16.     /**
  17.      * Creates an IntentService.  Invoked by your subclass's constructor.
  18.      */
  19.     public MyService() {
  20.         super("MyService");
  21.     }
  22.  
  23.     @Override
  24.     protected void onHandleIntent(@Nullable Intent intent) {
  25.         try {
  26.             URL myUrl = new URL("https://opentdb.com/api.php?amount=1&category=32&difficulty=hard&type=multiple");
  27.             InputStream stream = myUrl.openConnection().getInputStream();
  28.             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
  29.             StringBuilder builder = new StringBuilder();
  30.             String line;
  31.             while ((line = bufferedReader.readLine()) != null) {
  32.                 builder.append(line).append('\n');
  33.             }
  34.             LocalBroadcastManager localBroadcastManager =LocalBroadcastManager.getInstance(this);
  35.             Log.d("Service", "onReceive: Avem intrebarea!");
  36.  
  37.             Intent myIntent = new Intent("send_intrebare");
  38.             myIntent.putExtra("intrebare", builder.toString());
  39.             localBroadcastManager.sendBroadcast(myIntent);
  40.         } catch (MalformedURLException e) {
  41.             e.printStackTrace();
  42.         } catch (IOException e) {
  43.             e.printStackTrace();
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement