I have this IntentService (HttpService) which fetches raw json data from a webservice:
public class HttpService extends IntentService {
public static final String BROADCAST_ACTION = "com.example.HttpService";
public HttpService() {
super("HttpService");
}
#Override
protected void onHandleIntent(Intent intent) {
//code to get a String with jsonData
//Then I send a broadcast
Intent broadcastHttpResponseIntent = new Intent();
broadcastHttpResponseIntent.setAction(BROADCAST_ACTION);
broadcastHttpResponseIntent.putExtra("jsonData", jsonData);
sendBroadcast(broadcastHttpResponseIntent);
}
}
Now from the IntentService that uses HttpService I'm trying to get the broadcast:
public class RestaurantModel extends IntentService {
public static final String BROADCAST_ACTION = "com.example.RestaurantModel";
public RestaurantModel() {
super("RestaurantModel");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.v("RestaurantModel", "onHandleIntent");
BroadcastReceiver httpBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.v("RestaurantModel", "onReceive");
String jsonResponse = intent.getStringExtra("jsonData");
}
};
Intent getRestaurantsJsonIntent = new Intent(RestaurantModel.this, HttpService.class);
getRestaurantsJsonIntent.putExtra("urlRestaurants", intent.getStringExtra("urlRestaurants"));
startService(getRestaurantsJsonIntent);
registerReceiver(httpBroadcastReceiver, new IntentFilter(HttpService.BROADCAST_ACTION));
}
}
SO I'm getting this error:
RestaurantModel has leaked IntentReceiver com.example.RestaurantModel$1#42374590 that was originally registered here. Are you missing a call to unregisterReceiver()?
So I tried unregistering the Receiver but it seems to need a Context to unregister the receiver.
How to receive values from an IntentService into another IntentService?
The best answer is: have only one IntentService.
The next-best answer is: get rid of the broadcast stuff entirely, and have the first IntentService call startService() to kick off the second IntentService.
Agree with #CommonsWare, in case you want to use BroadcaseReceiver inside of an IntentService, register it in the onCreate method and unregister it in the onDestroy method.
public class RestaurantModel extends IntentService {
public static final String BROADCAST_ACTION = "com.example.RestaurantModel";
private BroadcastReceiver httpBroadcastReceiver;
public RestaurantModel() {
super("RestaurantModel");
}
#Override
public void onCreate() {
super.onCreate();
httpBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.v("RestaurantModel", "onReceive");
String jsonResponse = intent.getStringExtra("jsonData");
}
};
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(httpBroadcastReceiver);
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(httpBroadcastReceiver);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.v("RestaurantModel", "onHandleIntent");
Intent getRestaurantsJsonIntent = new Intent(RestaurantModel.this, HttpService.class);
getRestaurantsJsonIntent.putExtra("urlRestaurants", intent.getStringExtra("urlRestaurants"));
startService(getRestaurantsJsonIntent);
}
}
Related
I am using a LocalBroadcastManager to make broadcast to my activtiy and services using APPLICATION CONTEXT , like this:
public class CommonForApp extends Application{
public void broadcastUpdateUICommand(String[] updateFlags,
String[] flagValues) {
Intent intent = new Intent(UPDATE_UI_BROADCAST);
for (int i = 0; i < updateFlags.length; i++) {
intent.putExtra(updateFlags[i], flagValues[i]);
}
mLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext);
mLocalBroadcastManager.sendBroadcast(intent);
}}
Now Using a Listener in my Service, I am calling broadcastUpdateUICommand() ,like this:
public class mService extends Service {
public BuildNowPLaylistListListener buildCursorListener = new BuildNowPLaylistListListener() {
#Override
public void onServiceListReady() {
mApp.broadcastUpdateUICommand(
new String[] { CommonForApp.INIT_DRAWER},
new String[] {""});
}}}
And i am receiving the broadcast in my Activity, like this:
public class mActivity extends Activity{
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mtoast.showtext("in onreceive"); //toast to check
if (intent.hasExtra(CommonForApp.INIT_DRAWER))
initialiseDrawer();
}};
}
mApp is instance of Application.
CommonForApp is my Application Class.
But in my activity i am not receving any broadcast(the broadcast manager is initialised using application context) .
Can Anyone suggest me why i am not receiving broadcast in my activity? ..
.Thanks in advance !
in activity:
protected BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, final Intent intent) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(intent.hasExtra("type")){
// Do some action
}
}
});
}
};
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("data-loaded"));
}
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
then you send broadcast:
public static void sendBroadcastMessageDataLoaded(Context context, String dataType){
Intent intent = new Intent("data-loaded");
intent.putExtra("type", dataType);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
I IntentService that I would like to send message to the main Activity it is nested in. I am using a broadcast receiver to broadcast the message I got from the IntentService as such:
public static class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "com.mypackage.intent.action.MESSAGE_PROCESSED";
#Override
public void onReceive(Context context, Intent intent) {
String text;
text = intent.getStringExtra(RegistrationIntentService.PARAM_OUT);
regid = text;
}
}
I have registered the receiver in the Oncreate method of the main Activity. How can I send the "text" in this case? It is weird that regid in this case is null while "text" has the string data I wanted.
you can user result receiver with intent service to get the result into activity or fragment, follow the following links,
http://sohailaziz05.blogspot.in/2012/05/intentservice-providing-data-back-to.html
In your service you do
Intent intent = new Intent();
intent.setAction(yourActionToMatchBroadcastReceiverIntentFilter);
intent.putExtra(RegistrationIntentService.PARAM_OUT, yourText);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
In activity register your BroadcastReceiver in onResume() and unregister it in onPause(). Whenever your activity is active the receiver will receive intents from your IntentService.
EDIT
public static class ResponseReceiver extends BroadcastReceiver {
MapActivity activity;
public ResponseReceiver(MapActivity activity) {
this.activity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
activity.regid = intent.getStringExtra(RegistrationIntentService.PARAM_OUT);
// do whatever you need here
}
}
When registering, this was what worked for me
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
as opposed to
registerReceiver(receiver, filter);
#Override
public void onReceive(Context context, Intent intent) {
final String text = intent.getStringExtra(RegistrationIntentService.PARAM_OUT);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//access the string text and send it to backend
}
});
}
I hope this will help someone. Sending the string like suggested in the comments didn't work for me. I was getting nullpointerexception at that specific line where I assigned ma.regid = text;
I have a service and the main activity. Is there any way I can share a String in particular between these two. I have a method in the MainActivity that has to be executed only after the String from the service arrives. Is there any way of doing the same.
Thanks.
The following code will allow your Service to publish a String to your Activity. If you need to send data in the other direction use a more casual approach such as startService(Intent).
Setup a local BroadcastReceiver in your Activity:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (!MyService.ACTION_NEW_STRING.equals(intent.getAction()) return;
String myString = intent.getStringExtra(MyService.EXTRA_STRING);
// do whatever you need to do here
}
}
#Override
public void onStart() {
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mReceiver, new IntentFilter(MyService.ACTION_NEW_STRING));
}
#Override
public void onStop() {
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(mReceiver);
}
In your Service declare needed constants:
public static final String ACTION_NEW_STRING = "your_application_id.ACTION_NEW_STRING";
// or BuildConfig.APPLICATION_ID + ".ACTION_NEW_STRING" in Android Studio
public static final String EXTRA_STRING = "EXTRA_STRING";
private LocalBroadcastManager mManager;
#Override
public void onCreate() {
mManager = LocalBroadcastManager.getInstance(getApplicationContext());
}
In your service once you have your new String:
Intent i = new Intent(ACTION_NEW_STRING);
i.putExtra(EXTRA_STRING, myString);
mManager.sendBroadcast(i);
More reading on this topic: http://developer.android.com/reference/android/content/BroadcastReceiver.html
In my Application I have to notify my Activity from IntentService class .
For that purpose I am using LocalBroadcastManager. But I am not receiving anything in the onReceive of my Broadcast Receiver. Here is what I have written.
In my BaseActivity I have registered my receiver.
public class BaseActivity extends FragmentActivity implements App {
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(custom-event-name));
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mMessageReceiver);
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
System.out.println("Overlay Message" +bundle.getString("message"));
}
};
}
I am sending a local broadcast from my RegisterAlarmIntentService class.
public class RegisterAlramIntentService extends WakefulIntentService implements
APIConstants {
public RegisterAlramIntentService() {
super("AlarmService");
}
#Override
public String getTag() {
return "AlarmService";
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("Working till here fine In RegisterAlarm");
Bundle bundle = intent.getExtras();
Intent localIntent = new Intent(custom-event-name);
localIntent.putExtras(bundle );
LocalBroadcastManager.getInstance(this).sendBroadcast(
localIntent);
}
}
onHandleIntent() method is called. But nothing is received in onReceive() of my receiver.
Please Help. Thanks in advance!!
Try
public class RegisterAlramIntentService extends WakefulIntentService implements
APIConstants {
Intent localIntent;
public RegisterAlramIntentService() {
super("AlarmService");
localIntent = new Intent(custom-event-name);
}
#Override
public String getTag() {
return "AlarmService";
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("Working till here fine In RegisterAlarm");
Bundle bundle = intent.getExtras();
Thread.sleep(5000); // For Testing only because it is in whole new thread (which may not wait for your reciever to setup)
localIntent.putExtras(bundle );
LocalBroadcastManager.getInstance(this).sendBroadcast(
localIntent);
}
}
Also in manifest :
<service android:name="com.commonsware.android.localcast.RegisterAlramIntentService"/>
See this
I have a service that listens for (ON_BATTERY_CHANGE), then onReceive service sends a Broadcast to My MainActivity. The problem is that I somehow can't get them from service to my main activity. Code: Main Activity:
public class MainActivity extends Activity
private BroadcastReceiver batteryReceiverService;
private TextView text2;
....
protected void onCreate(Bundle savedInstanceState) {
text2=(TextView)findViewById(R.id.TV_text2);
batteryReceiverService = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
text2.setText("left: "+intent.getStringExtra("H")+" hours "+intent.getStringExtra("M")+" minute(s)");
Log.e("text2","text2 HHH " +intent.getStringExtra("H")); //log shows 0
Log.e("text2","text2 MMM " +intent.getStringExtra("H")); // log shows 0
}
};
registerReceiver(batteryReceiverService, new IntentFilter(UltimateBatterySaverService.BROADCAST_ACTION));
....
#Override
protected void onDestroy() {
unregisterReceiver(batteryReceiverService);
super.onDestroy();
}
Service:
public class UltimateBatterySaverService extends Service {
private Intent intent;
static final String BROADCAST_ACTION = "lt.whitegroup.ultimatebatterysaver";
private BroadcastReceiver batteryLevelReceiver;
....
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onDestroy() {
unregisterReceiver(batteryLevelReceiver);
super.onDestroy();
}
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryLevelReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent){
// Receiving data, calculating and etc
averageChargingH=timeAllInHours;
averageChargingM=timeAllInMinutes;
// to put extras and send broadcast
does();
......
public void does(){
String strLong = Long.toString(averageChargingH);
String strLong2 = Long.toString(averageChargingM);
Log.e("cccccc","strLong h "+strLong); // getting good value not 0(everything ok)
Log.e("cccccc","strLong2 m"+strLong2); // getting good value not 0(everything ok)
intent.putExtra("H", strLong);
intent.putExtra("M", strLong2);
sendBroadcast(intent);
}
Any ideas why my information is not transfered correctly?
The does() method seems to be using variables in the same scope as onReceive so I'm guessing that the intent variable in does() is actually the Intent passed in from onReceive.
Try adding some logging before sending the broadcast to check if the action of the intent is correct, or simply create the broadcast intent in the onReceive method and name it intent2.