0

I have created an intent download service and I want to pass download data to Toast and into Text in main activity. Download service should start from alarm manager repeatedly. How do I do this?

Currently, it does not show in Toast, but I have network traffic; data is downloaded but not shown.

Relevant code:

   public class DownloadService extends IntentService {

public String response;

  public DownloadService() {
    super("DownloadService");
  }

  // Will be called asynchronously be Android
  @Override
  protected void onHandleIntent(Intent intent) {

    //String urldown = intent.getStringExtra("url");
    String urldown="http://......";

        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(urldown);
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();

          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;
          }

    } catch (IOException e) {
      e.printStackTrace();
    }
         Intent intentsend=new Intent("update");
          intentsend.putExtra( "downdata",response);
          sendBroadcast(intentsend); 
  }
  • 1
    Why do you use toasts? Notifications are usually used when you need to show some kind of feedback from service. – Mikita Belahlazau Jan 14 '13 at 15:58
  • How i do this?And how i pass the download data to main.xml as text? – user1977741 Jan 14 '13 at 16:02
  • 1
    If you need two-way communication between service and activity - you can bind service to activity. Check [this](http://stackoverflow.com/questions/4300291/example-communication-between-activity-and-service-using-messaging) question. – Mikita Belahlazau Jan 14 '13 at 16:07

2 Answers2

1

This can be implemented with BroadcastReceiver:

In your activity, add the following code:

private BroadcastReceiver updateReceiver;

//...

@Override
protected void onResume() {
    super.onResume();

    updateReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //get extras, do some stuff
        }
    };
    IntentFilter updateIntentFilter=new IntentFilter("update");
    registerReceiver(updateReceiver, updateIntentFilter);
}

@Override
protected void onPause() {
    super.onPause();

    if (this.updateReceiver!=null)
        unregisterReceiver(updateReceiver);
}

And then, in your IntentService, just send broadcast with the same action:

Intent intent=new Intent("update");
intent.putExtra(...);
sendBroadcast(intent);
Andrii Chernenko
  • 9,873
  • 7
  • 71
  • 89
0

For me personally the receiver was not working so instead I created a singleton class where I was using the setter methods to set variables and the getter methods to get them to the particular activity.

Anninos Kyriakou
  • 205
  • 3
  • 15