What can be wrong in IntentService
-
13-12-2019 - |
Question
I have successfully used IntentService a few times, but in the current app, I can't get BroadcastReceiver's onReceive() to start. I have the exact String in Intent's action of the IntentService and in the IntentFilter which was registered in onResume along with the BroadcastReceiver.
filter = new IntentFilter("com.currencyconverter2.intent.action.MESSAGE");
Log.d("CC2", "intent filter created");
filter.addCategory(Intent.CATEGORY_DEFAULT);
Log.d("CC2", "filter category added");
receiver = new MessageReceiver();
Log.d("CC2", "receiver instantiated");
}
public void onResume(){
super.onResume();
registerReceiver(receiver, filter);
Log.d("CC2", "receiver registered");
}
public void onPause(){
super.onPause();
unregisterReceiver(receiver);
Log.d("CC2", "receiver unregistered");
}
public class MessageReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent){
Log.d(Tag, "entered onReceive...");
String html = intent.getStringExtra("OUTPUT");
webView.setBackgroundColor(Color.parseColor("#f4f36f"));
webView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
}
}
I also specified the service in Manifest.xml.
<service android:name=".IntentServiceTest"></service>
My Log tells me that the intentBroadcast was broadcasted from the IntentService, and the app stopped there. BroadcastReceiver didn't seem to have received it. What can be wrong? Thanks!
Edit:
My IntentService
Intent broadcastIntent = new Intent();
Log.d(Tag, "setting intent action");
broadcastIntent.setAction("com.currencyconverter2.intent.action.MESSAGE");
Log.d(Tag, "adding intent category");
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
Log.d(Tag, "putting intent extra");
broadcastIntent.putExtra("OUTPUT", data.text());
Log.d(Tag, "sending broadcast");
sendBroadcast(intent);
}catch(Exception e){
e.printStackTrace();
//System.out.println("f");
}
}
}
Edit 2:
Found the bug.
Intent broadcastIntent = new Intent();
Log.d(Tag, "setting intent action");
broadcastIntent.setAction("com.currencyconverter2.intent.action.MESSAGE");
Log.d(Tag, "adding intent category");
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
Log.d(Tag, "putting intent extra");
broadcastIntent.putExtra("OUTPUT", data.text());
Log.d(Tag, "sending broadcast");
sendBroadcast(intent);
I should have sendBroadcast(broadcastIntent); instead.
Solution
Check your AndroidManifest.xml:
<receiver android:name=".MessageReceiver">
<intent-filter>
<action android:name="com.currencyconverter2.intent.action.MESSAGE" />
<category android:name="android.intent.category.Default" />
</intent-filter>
</receiver>
^-^
OTHER TIPS
IntentService use to do task and shut it out, But as par your code it seems u are using long running time, use Service instead of IntentService