Service and Activity accessing shared data - android

I have an Activity that starts a service. I would like the service to have access 1 of the Activity's member variables(a boolean). I have implemented a getBoolean() method in the Activity, but how do I instantiate the Activity in the service for it to access?

Use SharedPreferences to save data in activity and yu can access it in service
in OnStartCommand method when you start a service
SharedPreferences sharedPref = getSharedPreferences("MYPREF", Context.MODE_PRIVATE);
sharedPref.getBoolean("flag",false);

You don't. Instead, use a broadcast receiver or shared preferences.
Example using broadcast receiver -
public class MyService extends Service {
boolean mActivityBoolean;
BooleanReceiver mReceiver;
#Override
public void onCreate() {
super.onCreate();
mReceiver = new BooleanReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(
mReceiver, new IntentFilter("activityBooleanIntent")
);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
super.onDestroy();
}
public class BooleanReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
mActivityBoolean = intent.getBooleanExtra("activityBoolean", false);
}
}
}
public class MyActivity extends Activity {
void someMethodThatSendsABooloean(boolean trueOrFalse) {
.....
Intent intent = new Intent();
intent.setAction("activityBooleanIntent");
intent.putExtra("activityBoolean", trueOrFalse);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}

Related

How to run function with broadcastreceiver in Android?

I have a function in activity I want to run this function with broadcastreceiver. How can I make this?
public class Myclass extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
}
}
This is my broadcastreceiver class I want to run function which is in my activty please tell me with some code how to do this.
If the method you want to execute needs your activity instance, then you can register the broadcast receiver inside your activity, so it can access your activity's state and functions.
In your Activity "onCreate" method:
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("Your Intent action here");
intentFilter.addAction("Another action you want to receive");
final BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
theFunctionYouWantToExecute();
}
};
registerReceiver(myReceiver, intentFilter);
And in your "onDestroy" method:
unregisterReceiver(myReceiver);
Keep in mind that in this case your broadcast receiver has full access to your activity state, BUT it's lifecycle will be conditioned to the activity lifecycle.
Another option you have is to declare your activity method as static, so you can execute it in any part of your application.
You can declare an interface in Myclass and implement it in your MainActivity
public class Myclass extends BroadcastReceiver{
public interface MyClassInterface {
void onMyClassReceive();
}
private MyClassInterface mListener;
public Myclass(MyClassInterface mMyClassInterface) {
mListener = mMyClassInterface;
}
#Override
public void onReceive(Context context, Intent intent) {
mListener.onMyClassReceive();
}
}
Then in your MainActivity:
public class MainActivity implements Myclass.MyClassInterface {
private mMyClass Myclass = new Myclass(this);
#Override
public void onMyClassReceive() {
// Do stuff when Myclass.onMyClassReceive() is called,
// which will be called when Myclass.onReceive() is called.
}
}
You are almost there. Just create your method in the Activity and using Activity's instance call that method. Remember that your method inside your Activity should be not private.
public class Myclass extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
new YourActivity().yourFunction();
}
}
If you want to create a static method inside your Activity then
public class Myclass extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
YourActivity.yourFunction();
}
}
To trigger the Broadcast, you have to pass an Intent. If you want to trigger it from any Activity then
Intent intent = new Intent();
this.sendBroadcast(intent);
If you want to trigger the Broadcast from a Fragment then
Intent intent = new Intent();
getActivity().sendBroadcast(intent);
I know it's quote naif, but you could call a static method in your activity.
In your activity you declare the method like this:
public static <return_type> yourMethod(<input_objs>){
....
Your code
....
}
In the receiver you can use this function just calling:
YourActivityClass.yourMethod(<input_objs>);
I hope it helped.

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

Interaction between Activity and Sticky Service

i have an Activity and a Sticky Service. The Activity needs to show some values in it´s UserInterface depending on the values of the Sticky Service. So whenever the Service changes his data, the Activity needs to update it´s UserInterface.
But how should the Service notify the Activity to change it´s values??
Please remind that the Activity sometimes isn´t alive, only the Service is Sticky.
Use LocalBroadcasts
in your service class:
public class LocalMessage extends IntentService{
private Intent broadcast;
public static final String BROADCAST = "LocalMessage.BROADCAST";
public LocalMessage(String name) {
super(name);
broadcast = new Intent(name);
}
#Override
protected void onHandleIntent(Intent intent) {
if (broadcast != null) LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast);
}
}
and here is method inside service to broadcast
private void sendLocalMessage(){
(new LocalMessage(LocalMessage.BROADCAST)).onHandleIntent(null);
}
In your activity:
private void registerBroadcastReciever() {
IntentFilter filter = new IntentFilter(YourService.LocalMessage.BROADCAST);
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(receiver, filter);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//doSmth
}
};
in your activity onDestroy() method unregister receiver;

sending intent extras from service to activity

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.

Communication between C2DM BroadcastReceiver and multiple activities

I have an Android application which uses C2DM services (aka push).
I have a separate class which implements the registration process and which receives the data (and extends BroadcastReceiver).
I want to communicate this data to the activity which currently is in the foreground. The activity currently in the foreground may differ depending on user action.
What's the best way to communicate in between the receiver and the current activity?
Thanks.
I solved this problem by sending out a new broadcast from the C2DMReceiver class, which looked something like this.
The C2DMReceiver class:
public class C2DMReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
handleRegistration(context, intent);
} else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(context, intent);
}
}
private void handleRegistration(Context context, Intent intent) {
// handle registration
}
private void handleMessage(Context context, Intent intent) {
Intent i = new Intent("push");
i.putExtras(intent);
// context.sendOrderedBroadcast(i, null);
context.sendBroadcast(i);
}
}
Another class I called PushReceiver. This is the class that will extend BroadcastReceiver and receive the broadcast sent by C2DMReceiver.
public class PushReceiver extends BroadcastReceiver {
public PushReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
// do stuff
abortBroadcast();
}
public static class PushFilter extends IntentFilter {
private static final int DEFAULT_PUSH_PRIORITY = 1;
public PushFilter() {
this(DEFAULT_PUSH_PRIORITY);
}
public PushFilter(int priority) {
super("push");
setPriority(priority);
}
}
}
And the activity class, in this case called MyActivity. This should work well if you are using a base activity class that all other activities extend. That way every activity registers the receiver. By doing the register/unregister in onResume/onPause, you should be able to guarantee that only the current activity receives the broadcast. If not, you can send an ordered broadcast from C2DMReceiver and use priority in the PushFilter.
public class MyActivity extends Activity {
private PushReceiver pushReceiver;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// your onCreate method
pushReceiver = new PushReceiver();
}
public void onResume() {
super.onResume();
// your onResume method
registerReceiver(pushReceiver, new PushReceiver.PushFilter());
}
public void onPause() {
super.onPause();
// your onPause method
unregisterReceiver(pushReceiver);
}
}
In my case, I wrote the PushReceiver constructor to take a View and then "did stuff" with the view in the onReceive method. Without knowing more about what your trying to do, I can't elaborate on this, but hopefully this can provide a decent template to work from.

Categories

Resources