sending intent extras from service to activity - android

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.

Related

Broadcast data from FCM while app is in foreground not getting in BroadcastReceiver

I am using firebase push notification in my app,In case of app in foreground, i am broadcasting an intent to another activity on receiving the message. But i am not getting the intent in the BroadcastReceiver written in the directed activity.
sending intent is like
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (isAppIsInBackground(this)){
int dbcount = Integer.parseInt(dbHelper.getPushCount());
int i = count;
int current = dbcount +4;
dbHelper.updatePushCount(Integer.toString(current));
} else {
Intent intent = new Intent(this, NavigationHome.class);
intent.setAction("new.pushMessage");
intent.putExtra("count", count.toString());
sendBroadcast(intent);
}
}
and receiver in the activity in which i want to get the intent is
public class NavigationHome extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {
int count=0;
Context context;
private BroadcastReceiver LandingBr = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("received",""+1);
NavigationHome.this.update();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_home);
dbhelper = new DBHelper(this);
...................
update() function is not getting called, How can i get the intent in the Activity?
Create MyReceiver class extending BroadcastReceiver in activity.
class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// do your stuff here
}
}
and than register your BroadcastReceiver in onCreate() of Particular activity . use following code for that.
MyReceiver myReceiver =new MyReceiver();
IntentFilter intentFilter= new IntentFilter(Constants.ACTION);
registerReceiver(myReceiver,intentFilter);

Android: how to have a localbroadcast reciever inside service

I have service in which I want to have a localbroadcast receiver. I want to recieve a value from the activity to my services onCreate.
Note: I can get a value from an activity to my service in onStartCommand() using intent. But here I want a value from activity in onCreate of the service.
The following is my service file:
public class MediaServiceSimha extends Service {
private MediaPlayer player;
String musicpath;
private ResponseReceiver receiver;
public MediaServiceSimha() {}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#
Override
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
super.onCreate();
IntentFilter broadcastFilter = new IntentFilter("com.example.myintentserviceapp.intent_service.ALL_DONE");
receiver = new ResponseReceiver();
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.registerReceiver(receiver, broadcastFilter);
}
public class ResponseReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
musicpath = intent.getStringExtra("musicpath");
}
}
}
The following is my activity file where I want to pass a value called musicpath
public class ServiceTest extends AppCompatActivity {
Intent intent;
public static final String TEXT_INPUT = "inText";
//MediaServiceSimha mediaServiceSimha;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
L.m("activity_oncreate_starting");
setContentView(R.layout.activity_service_test);
intent= new Intent(this,MediaServiceSimha.class);
startService(intent);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.example.myintentserviceapp.intent_service.ALL_DONE");
broadcastIntent.putExtra("musicpath", "/storage/emulated/0/Download/1.mp3");
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(broadcastIntent)
}
}
After running, it says musicpath value is null.
How to do it?
My goal was to pass a variable value directly to oncreate in the service class.
I tried LocalBroadcast's reciver and also onbindservices - onServiceConnected
Both of them i found that they will only get executed untill oncreate -> onbind/onstartcommand get executed in the services.
So only option left is onstartcommand()
So when we pass values using intent then they can be used immediately inside onstartcommand.
when you are calling start service it doesn't mean it will call immediately,so wait for oncreate of service,whenever your service getstarted you can send a callback to your activity then you can broadcast values to your service
public service callback() // callback from service started
{
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.example.myintentserviceapp.intent_service.ALL_DONE");
broadcastIntent.putExtra("musicpath", "/storage/emulated/0/Download/1.mp3");
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(broadcastIntent)
}
public class MediaServiceSimha extends Service {
#Override
public void onCreate() {
super.onCreate();
IntentFilter broadcastFilter = new IntentFilter("com.example.myintentserviceapp.intent_service.ALL_DONE");
receiver = new ResponseReceiver();
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.registerReceiver(receiver, broadcastFilter);
sendCallback(); // using interface or broadcast receiver to send callback to activity
}
}

How to receive values from an IntentService in another IntentService?

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);
}
}

Android pass message from IntentService to Activity

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;

How to Start same activity with different data from Broadcast Receiver?

I have 1 activity that I would like to start at different times with different variables from a Broadcast Receiver.
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase("tv.abcd.v4.ORIGINAL_VIDEO_SCENE")){
channelName = intent.getExtras().getString("com.abcd.Channel");
JSONObject json = new JSONObject(intent.getExtras().getString("com.abcd.Data"));
String incomingScene = json.getString("url");
scene.putExtra("channel", channelName);
scene.putExtra("url", incomingScene);
scene.addFlags(Intent.FLAG_FROM_BACKGROUND);
scene.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
scene.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scene);
}
I have the code to start the activity via Intent and in the activity receiver the extras to make data appear.
Intent intent = getIntent();
sceneUrl = intent.getStringExtra("url");
Log.d("Image.incomingscene.url",sceneUrl);
channelName = intent.getStringExtra("channel");
Log.d("Image.incomingSceneAvatar",networkAvatar);
image = (ImageView)findViewById(R.id.imageView1);
image.setScaleType(ScaleType.FIT_CENTER);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
Picasso.with(this).load(sceneUrl).skipMemoryCache().fit().into(image, new EmptyCallback() {
});
Now after that I want to start the same activity again from the Broadcast Reciever with different data. So i want the previous activity to get out the way and allow this new instance to start up.
How to accomplish this feat?
register another broadcast receiver from the activity. Then, when you want to kill it, send a broadcast message from the broadcast receiver that you mentioned .
In your broadcastReceiver do something like the following :
public static final String CLOSE_Activity= "com.mypackage.closeactivity";
and in yopr OnReceive method do like the following :
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("HIT OUTGOING");
Intent i = new Intent();
i.setAction(CLOSE_Activity);
context.sendBroadcast(i);
}
then in your activity craete a receviver and register it in the onResume method and unregeister it in the onPause method , like the following :
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(RECEIVER_Class.CLOSE_Activity)) {
finish();
}
}
}
activity onResume method :
#Override
public void onResume() {
registerReceiver(broadcastReceiver, new IntentFilter(RECEIVER_Class.CLOSE_Activity));
}
activity onPause method :
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Please give me some feedback
Hope that helps .

Categories

Resources