意图服务中的广播接收器

4
我正在尝试在我的IntentService的onHandleIntent()方法中注册DownloadManager.ACTION_DOWNLOAD_COMPLETE接收器,并在IntentService的onDestroy()方法中取消注册接收器。但是我认为它没有被注册,因为一旦下载完成,接收器的onReceive()方法没有被触发。 有人能帮我解决这个问题吗?

2
一个 IntentServiceonHandleIntent() 结束后立即被销毁。一个写得好的 IntentService 只运行了很短的时间,所以你只会在短时间内收到这个广播。 - CommonsWare
哦,好的。那么有什么替代方案吗?因为我需要在后台下载文件。 - Vinay Mundada
1
由于我不知道您正在使用 IntentService 的目的,因此我无法告诉您答案是“不要使用 IntentService”还是“在其他地方注册接收器,例如清单文件中”。 - CommonsWare
基本上我想运行一个定时服务(比如每隔24小时),在这个服务中,我将使用DownloadManager来下载文件。那么在我使用的IntentService中,我该如何注册和注销接收器呢? - Vinay Mundada
在清单文件中注册接收器。如果需要,可以在其上设置 android:enabled="false",然后在需要时使用 setComponentEnabledSetting() 来启用您的 IntentService - CommonsWare
2个回答

3
创建服务类:
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();
}

在活动中,

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

创建接口,实现在活动中,并定义下载完成后要执行的功能。
    public interface IConnectionCallback {
     void finishDownload();

  }

最后,在清单文件中注册服务:

    <receiver android:name=".ConnectionBroadReceiver">

0
以下代码可从这里获取:
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();
        }
    }

}

在清单文件中创建服务。


写一个关于链接内容的摘要。将来,链接可能会失效。 - Green goblin
如果您在答案中复制/粘贴代码,请始终添加归属。此外,仅代码答案不被鼓励,应添加解释该代码如何解决问题的描述! - Daniel Nugent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接