Android: How to pass data from service to broadcast reciever - android

In my laboratory work I have to create a service, which sends notifications when speed of battery discharging is greater then set.
I created an Activity with EditText for this value and 2 button for starting and stopping the service. Also I created a BatteryService class, inherited form Service class and BatteryReciever.
Now reciver registers with action BATTERY_CHANGED in service in onStartCommand. And problem is how to pass data to reciever or how to know about events in service.
What is the best way to solve this task?

To trigger a BroadcastReceiver, you need to use
sendBroadcast(intent);
Put the data you want to send from the Service in the intent as follows:
Intent intent = new Intent("my.custom.action");
Bundle b = new Bundle();
b.putSerializable("name", name);
b.putShort("count", count);
intent.putExtra("bundle", b);
sendBroadcast(intent);
And retrieve the data in the onReceive() method of the BroadcastReceiver:
#Override
public void onReceive (Context context, Intent intent){
Bundle b = intent.getExtras();
// do awesome things ...
}
Try this. This will work.

Related

Get view of activity and fragments from service

I have on my app a service who get my location (gps). This service get information like latitude, longitude, etc, and I want wrote these information in layouts fragment and activity (TextView).
But how can I get view reference of theses fragments since my service ?
You can do one thing to achieve this. send broadcast to the activity. And on that activity where you want to update view register broadcast there. Once you get the location stuff then send broadcast. Hope that helps you. Write this code in service when you get location stuff and pass that stuff via intent as mentioned in below code
Intent broadcastIntent = new Intent(your action here);
broadcastIntent.putExtra(BaseBroadCastReceiver.BROADCAST_KEY_AUDIO_INDEX, audioIndex);
broadcastIntent.putExtra(BaseBroadCastReceiver.BROADCAST_KEY_AUDIO_LIST, mSongList.size());
sendBroadcast(broadcastIntent);
And in your activity write below code
private void registerMyReceiver() {
IntentFilter filter = new IntentFilter(your action here you passed in service);
registerReceiver(playNewAudio, filter);
}
NOTE: your action can be any string but string must be same on both side
When activity's oncreate method is called, call registerMyReceiver() method
and in onDestroy method unregister is else you may get RUNTIME exception.
Below will be your code for actual broad cast receiver
private BroadcastReceiver myBroadcast= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//do your stuff here... get extra which you passed
// from service and set that value in views
}
};

Be notified when Service is started

I have a Service that scans for BLE devices. The Activity should show some data gathered by the Service.
A Receiver has been implemented, to be notified when the Bluetooth is enabled, so that we know when to start the Service.
If the Service is running, and the Activity is opened, it just executes bindService(). However, if the Service isn't running (because the Bluetooth is disabled), the App is opened and the Bluetooth is enabled, it won't bind because the binding process has already been skipped.
How can I be notified about the Service starting or automatically binding when started?
Thank you.
You can use the LocalBroadCastManager to send a broadCast from your service to your activity.
Helper to register for and send broadcasts of Intents to local objects within your process. This has a number of advantages over sending global broadcasts with sendBroadcast(Intent):
You can use localbroadcast reciever from your service.
In your service use these code
intent = new Intent("my-integer");
intent.putExtra("message",""+a);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
In your activity use this code
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String data = intent.getStringExtra("message");
if (!data.equals("0")) {
//Do something
} else {
//Do something else
}
}
}
};

Android Change a variable in service from other app

the title says all, I need to change the variable of my service from a activity in my other app , what to finalize the service or not, this is possible?
I found the Message object , but I do not quite understand
The simplest solution would be to implement a BroadcastReceiver. Your Service listens for the Broadcast and the other App sends the Broadcast.
Example Reciever:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Get bundle from intent and use it to set your Variable in your Service
}
}
Example Broadcaster (courtesy of Vogella):
Intent intent = new Intent();
intent.setAction("de.vogella.android.mybroadcast");
sendBroadcast(intent);

How to let Activity know that cyclic Service has finished its task once?

I have some problems working with Android Services. I already have a Service which downloads a file from a server. (The Service checks cyclic for new data) Aftwerwards it parses the file and adds values to an ArrayList wich will be saved to SharedPreferences.
In my Activity there are two methods. One will display the values from the ArrayList/SharedPreferences in UI and the second method sets a Notification if needed.
But how do I now when my Service completed its task so the two methods can be started?
Register a BroadcastReceiver in your Activity something like:
myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do my stuff
}
};
registerReceiver(myReceiver , new IntentFilter("com.myapp.DOWNLOADCOMPLETE"));
Then in your service send the broadcast:
Intent i = new Intent("com.myapp.DOWNLOADCOMPLETE");
sendBroadcast(i);
You can also putExtras on your intent if you need to pass some values:
Documentation BroadcastReceiver

Not getting the flow of below program

public class MainActivity extends Activity {
public TextView batteryTxt;
private BroadcastReceiver receiver;
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int batterylevel = intent.getIntExtra("level", 0);
batteryTxt.setText("Battery Level: " + Integer.toString(batterylevel) + "%");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
batteryTxt = (TextView) findViewById(R.id.textView1);
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(mybroadcast, filter);
}
}
Eventhough i have not used intent.putExtra() in above program, how intent.getIntExtra("level", 0) is working?
It's an IntentFilter, which sends an Intent to the BatteryManager to check ACTION_BATTERY_CHANGED. The BatteryManager then calls intent.putIntExtra to put the int that you're reciving in the Intent.
The intent is what your BroadcastReceiver receives from the system, when the action "ACTION_BATTERY_CHANGED" is performed. It's the information about battery level in this case, and "0" is the default value (in case there isn't extra named "level"). The intent is not created by any activity in this app.
You need to read the documentation on BroadcastReceivers and Intents.
http://developer.android.com/reference/android/content/BroadcastReceiver.html
http://developer.android.com/reference/android/content/Intent.html
Essentially these two mechanisms act as Android's preferred method of transferring state between applications and processes.
In short:
Broadcast Receivers are registered for Intents, and whenever an intent is "Fired" or "Launched" which corresponds to the "Mime-Type" for which your intent is registered, that Broadcast Receiver will be activated. At this time your Broadcast Receiver will be given the opportunity to handle state passed to it via the intent which was sent.
In your case:
You have created a Broadcast Receiver which is registered (presumably) for the Battery Service intents. That means every time the battery service sends out an Intent to all interested parties you'll receive an a message. The Battery Service includes in it's intent certain data which is useful to an application,service or process which is interested in the state of the Battery. In this case it is the "level".

Categories

Resources