4

I am trying to register the DownloadManager.ACTION_DOWNLOAD_COMPLETE receiver in onHandleIntent() method of my IntentService and unregistering the receiver in onDestroy() method of the IntentService. But I think its not getting registered, since the onReceive() method of the receiver is not getting triggered once the download is complete. Can anyone help me with this?

Vinay Mundada
  • 317
  • 3
  • 13
  • 2
    An `IntentService` is destroyed as soon as `onHandleIntent()` ends. A well-written `IntentService` only runs for a short while, so you will only be receiving this broadcast for a short while. – CommonsWare Jul 07 '16 at 13:20
  • Oh okay. So what is the alternative solution for this, since I need to download files in the background? – Vinay Mundada Jul 07 '16 at 13:23
  • 1
    Since I do not know what you are using the `IntentService` for, I cannot tell you if the answer is "do not use an `IntentService`" or "register your receiver somewhere else, such as in the manifest". – CommonsWare Jul 07 '16 at 13:26
  • Basically I want to run a scheduled service (say after every 24 hours) in which I will be using the DownloadManager to download files. So in the IntentService that I am using, how do I register and unregister the receiver? – Vinay Mundada Jul 07 '16 at 14:29
  • Register the receiver in the manifest. If you want, have `android:enabled="false"` on it, then have your `IntentService` use `setComponentEnabledSetting()` to enable it when needed. – CommonsWare Jul 07 '16 at 14:31

2 Answers2

3

Create service class,

public class ConnectionBroadReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        ConnectivityManager cm = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        IConnectionCallback callback = (IConnectionCallback) context;
        callback.finishDownload();
}

In Activity,

    ConnectionBroadReceiver broadReceiver = new ConnectionBroadReceiver();
    registerReceiver(broadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

Create Interface,and Implement in activity and define the function what you to do after downloading

    public interface IConnectionCallback {
     void finishDownload();

  }

And finaly register the service in manifest,

    <receiver android:name=".ConnectionBroadReceiver">
mehrdad khosravi
  • 2,228
  • 9
  • 29
  • 34
Priya
  • 672
  • 1
  • 5
  • 21
0

The code below is from here:

public class MyWebRequestService  extends IntentService{

public static final String REQUEST_STRING = "myRequest";
public static final String RESPONSE_STRING = "myResponse";
public static final String RESPONSE_MESSAGE = "myResponseMessage";

private String URL = null;
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;

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

@Override
protected void onHandleIntent(Intent intent) {

    String requestString = intent.getStringExtra(REQUEST_STRING);
    String responseString = requestString + " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());
    String responseMessage = "";
    SystemClock.sleep(10000); // Wait 10 seconds
    Log.v("MyWebRequestService:",responseString );

    // Do some really cool here
    // I am making web request here as an example...
    try {

        URL = requestString;
        HttpClient httpclient = new DefaultHttpClient();
        HttpParams params = httpclient.getParams();

        HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
        ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);

        HttpGet httpGet = new HttpGet(URL);
        HttpResponse response = httpclient.execute(httpGet);

        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseMessage = out.toString();
        }

        else{
            //Closes the connection.
            Log.w("HTTP1:",statusLine.getReasonPhrase());
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }

    } catch (ClientProtocolException e) {
        Log.w("HTTP2:",e );
        responseMessage = e.getMessage();
    } catch (IOException e) {
        Log.w("HTTP3:",e );
        responseMessage = e.getMessage();
    }catch (Exception e) {
        Log.w("HTTP4:",e );
        responseMessage = e.getMessage();
    }


    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(MyWebRequestReceiver.PROCESS_RESPONSE);
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra(RESPONSE_STRING, responseString);
    broadcastIntent.putExtra(RESPONSE_MESSAGE, responseMessage);
    sendBroadcast(broadcastIntent);

}

}

IntentFilter filter = new IntentFilter(MyWebRequestReceiver.PROCESS_RESPONSE);
    filter.addCategory(Intent.CATEGORY_DEFAULT);
    receiver = new MyWebRequestReceiver();
    registerReceiver(receiver, filter);


@Override
public void onDestroy() {
    this.unregisterReceiver(receiver);
    super.onDestroy();
}

public class MyWebRequestReceiver extends BroadcastReceiver{
    public static final String PROCESS_RESPONSE = "com.as400samplecode.intent.action.PROCESS_RESPONSE";
    @Override
    public void onReceive(Context context, Intent intent) {
        String responseString = intent.getStringExtra(MyWebRequestService.RESPONSE_STRING);
        String reponseMessage = intent.getStringExtra(MyWebRequestService.RESPONSE_MESSAGE);
        TextView myTextView = (TextView) findViewById(R.id.response);
        myTextView.setText(responseString);
        WebView myWebView = (WebView) findViewById(R.id.myWebView);
        myWebView.getSettings().setJavaScriptEnabled(true);
        try {
            myWebView.loadData(URLEncoder.encode(reponseMessage,"utf-8").replaceAll("\\+"," "), "text/html", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}

public class MyWebRequestService  extends IntentService{

public static final String REQUEST_STRING = "myRequest";
public static final String RESPONSE_STRING = "myResponse";
public static final String RESPONSE_MESSAGE = "myResponseMessage";

private String URL = null;
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;

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

@Override
protected void onHandleIntent(Intent intent) {

    String requestString = intent.getStringExtra(REQUEST_STRING);
    String responseString = requestString + " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());
    String responseMessage = "";
    SystemClock.sleep(10000); // Wait 10 seconds
    Log.v("MyWebRequestService:",responseString );

    // Do some really cool here
    // I am making web request here as an example...
    try {

        URL = requestString;
        HttpClient httpclient = new DefaultHttpClient();
        HttpParams params = httpclient.getParams();

        HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
        ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);

        HttpGet httpGet = new HttpGet(URL);
        HttpResponse response = httpclient.execute(httpGet);

        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseMessage = out.toString();
        }

        else{
            //Closes the connection.
            Log.w("HTTP1:",statusLine.getReasonPhrase());
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }

    } catch (ClientProtocolException e) {
        Log.w("HTTP2:",e );
        responseMessage = e.getMessage();
    } catch (IOException e) {
        Log.w("HTTP3:",e );
        responseMessage = e.getMessage();
    }catch (Exception e) {
        Log.w("HTTP4:",e );
        responseMessage = e.getMessage();
    }


    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(MyWebRequestReceiver.PROCESS_RESPONSE);
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra(RESPONSE_STRING, responseString);
    broadcastIntent.putExtra(RESPONSE_MESSAGE, responseMessage);
    sendBroadcast(broadcastIntent);

}

}

IntentFilter filter = new IntentFilter(MyWebRequestReceiver.PROCESS_RESPONSE);
    filter.addCategory(Intent.CATEGORY_DEFAULT);
    receiver = new MyWebRequestReceiver();
    registerReceiver(receiver, filter);


@Override
public void onDestroy() {
    this.unregisterReceiver(receiver);
    super.onDestroy();
}

public class MyWebRequestReceiver extends BroadcastReceiver{
    public static final String PROCESS_RESPONSE = "com.as400samplecode.intent.action.PROCESS_RESPONSE";
    @Override
    public void onReceive(Context context, Intent intent) {
        String responseString = intent.getStringExtra(MyWebRequestService.RESPONSE_STRING);
        String reponseMessage = intent.getStringExtra(MyWebRequestService.RESPONSE_MESSAGE);
        TextView myTextView = (TextView) findViewById(R.id.response);
        myTextView.setText(responseString);
        WebView myWebView = (WebView) findViewById(R.id.myWebView);
        myWebView.getSettings().setJavaScriptEnabled(true);
        try {
            myWebView.loadData(URLEncoder.encode(reponseMessage,"utf-8").replaceAll("\\+"," "), "text/html", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}

In Manifest Create service.

Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
Chirag Arora
  • 816
  • 8
  • 20
  • Write a summary on what the link contains. In future, the link might be dead – Green goblin Jul 07 '16 at 13:31
  • Always add attribution if you are copying/pasting code in an answer. Also, code only answers are discouraged, add a description of how this code solves the problem in the question! – Daniel Nugent Jul 07 '16 at 16:36