Ich versuche, die DownloadManager.ACTION_DOWNLOAD_COMPLETE Empfänger in onHandleIntent() Methode meiner IntentService und Aufheben der Registrierung der Empfänger in onDestroy() Methode des IntentService zu registrieren. Aber ich denke, es wird nicht registriert, da die Methode onReceive() des Empfängers nicht ausgelöst wird, sobald der Download abgeschlossen ist. Kann mir jemand dabei helfen?Broadcast-Receiver in einem IntentService
Antwort
Der folgende Code ist 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 Service erstellen.
Schreiben Sie eine Zusammenfassung darüber, was der Link enthält. In Zukunft könnte die Verbindung tot sein –
ok jetzt bearbeitet, danke für den Vorschlag. –
Fügen Sie Attributionen immer hinzu, wenn Sie Code in einer Antwort kopieren/einfügen. Auch Code-Only-Antworten werden abgeraten, fügen Sie eine Beschreibung hinzu, wie dieser Code das Problem in der Frage löst! –
Service-Klasse erstellen,
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 Aktivität
ConnectionBroadReceiver broadReceiver = new ConnectionBroadReceiver();
registerReceiver(broadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Schnittstelle erstellen und in Aktivität umsetzen und definieren die Funktion, was Sie nach dem Herunterladen
public interface IConnectionCallback {
void finishDownload();
}
zu tun
Und finaly den Dienst in manifest registrieren,
<receiver android:name=".ConnectionBroadReceiver">
Ein 'IntentService' wird, sobald' onHandleIntent() 'Ende zerstört. Ein gut geschriebener 'IntentService' läuft nur kurz, so dass Sie diese Sendung nur für kurze Zeit erhalten. – CommonsWare
Oh okay. Was ist die alternative Lösung dafür, da ich Dateien im Hintergrund herunterladen muss? –
Da ich nicht weiß, wofür Sie den 'IntentService' verwenden, kann ich Ihnen nicht sagen, ob die Antwort lautet:" Verwenden Sie keinen 'IntentService'" oder "registrieren Sie Ihren Empfänger woanders, wie im Manifest". – CommonsWare