Sharing simple data between two processes - android

I'm developing an android application, which when user enters licence code, retrieves from web service some simple key-value data and saves to sharedpreferences.
My app also have a service, which starts on separate process and it needs to get a part of previously saved data from sharepreferences.
My main app lets say is in "com.foo.myMainApp" package. And my service is "com.foo.myMainApp/myService".
The problem is, that the service can't access main program's shared prefs, because they are saved in different location.
I'm struggling with this problem for a couple of days and can't find a way out.
Any help would be appreciated.

Use BroadcastReceivers.
in Service
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("ACTION");
broadcastIntent.putExtra("MESSAGE", "hello");
sendBroadcast(broadcastIntent);
In MainACtivity
register this broadcast receiver and your good to go receiving messages.
private class Message extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// get the message here
}
}
// register this onStart
registerReceiver(new Message(),new IntentFilter("ACTION") );
hope this helps :)

Related

Running a bound service and a thread

I currently have a bound Service with my Main activity.
I was wondering if it was possible to have a Thread Running inside this bound Service that can pass integers to my Main Activity. This Service needs to auto update my Main Activity's Text View with any new Random number Integer without clicking a button.
Should i look into Handlers?? Or Message/ Bundles??
Any help would be appreciated ! Thank you !
You can define one Receiver your MainActivity and you can use send Broadcast to that receiver to update your UI.. That is a simple way to do it
In your service Just define one intent and put values into it like follwing
Intent i = new Intent();
i.setAction("RECEIVERACTION");
i.putExtra("data", "mydata");
sendBroadcast(i);
and in your activity
public static class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String data = intent.getStringExtra("data");
textView.setText(data);
}
}
Hope it helps!!!
Please go through api guides. Specifically
https://developer.android.com/guide/components/bound-services.html
https://developer.android.com/guide/components/services.html
This should give you a pretty good idea to move forward and also code samples

How can a background service know if activity is killed or not

I have an activity that starts a background service. Once it is started, it runs forever.
Lets say the background service needs the activity that started it to update something. Then how can I start the activity again "If it is not started" however if it is already started then send a broadcast?
Thanks
You would have to bind to the service in your activity. Then, in the service, implement the onBind and onUnbind methods to set a boolean "bound". Check the boolean to see whether the activity is active.
With activity you mean the service's process. If the service is started forever, then its process its started foerever (except when the system kill its for recovering memory purpose and recreates it later). That doesnt mean the rest of activities/fragments/services are not kill. A service is just an entry point for your application and it gives your process a position into the process priority ladder.
Its hard to say, since I don't know the details of your app, but I think that you may want to consider a bit of a redesign.
As you have noticed, Activities are ephemeral. Generally speaking, a service should not (cannot) depend on a particular Activity being active.
In fact, a well-designed service should not depend on any particular activity at all.
I'm not sure I completely follow your question. However, when communicating from a Service to an Activity I use a broadcast receiver in the Activity class.
This can be created as follows:
// register the BroadcastReceiver in your activity class
this.receiver = new NotificationReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.LISTENER");
registerReceiver(receiver, filter);
// insert in your activity class
class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.hasExtra("command")) {
if(intent.getStringExtra("command").equals("userRegistered")) {
// insert code to do something when this intent is received
}
}
}
}
// insert in your service class to send message
Intent i = new Intent("com.example.LISTENER");
i.putExtra("command", "userRegistered");
sendBroadcast(i);

How an android service interact with the activity

I'm developing a subway guide app, when reaching a new station, a notification will pop up, and the map shown in the main activity will refresh. I put the guide code in a service so that users can run other apps while being guided. But the main activity needs to be refreshed when reaching a new station, how can the service make some changes to the view in the main activity?
There are a couple of ways to do this.
You can bind the service with the activity.
You can send broadcast messages to the activity (the activity need to register with the Broadcast Reciever)
There are lot of discussions on this topic. You can go through them.
In your activity, you should register a receiver
Declare the receiver first
public class ReceiverTest extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
// extras from service
int key = intent.getIntExtra("key", 0);
//do things here
}
}
Register it in OnCreate of your activity
ReceiverTest mReceiver = new ReceiverTest();
IntentFilter filter;
filter = new IntentFilter("packagename.dosomething");
registerReceiver(mReceiver, filter);
Then, in your service, broadcast the event
Intent i = new Intent("packagename.dosomething");
// You could put the information in extras, then get the value in receiver
i.putExtra("key", 123);
context.sendBroadcast(i);
The best way to share data between the Service S and Activity A
Use the local binding pattern and have Activity A bind to Service S, then call the service's exposed API to retrieve whatever is needed.
How can the external activity B communicate with the Service S to determine if it has completed with all its preprocessing, and the Activity A is ready to be invoked?
Use the remote binding pattern and AIDL. Activity B would register an AIDL-defined callback with Service S, which the service would invoke when appropriate. See here and here for an example.

How can my service change values of variables and UI textfields of my activities?

I have an application that get/send data from/to a remote DB on internet.
I need to get my application working in background mode, then i supose that i have to put all the send/get remote data in a service.....
but.... How can this service change values of variables and UI textfields of my activities?
i can't find any information about this, all the tutorials i am finding are of simple services that doesn't do something like that
can someone explain me how to do it please?
Use a BroadcastReceiver
In your Activity place the following code:
private BroadcastReceiver onBroadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context ctxt, Intent i) {
// do stuff to the UI
}
};
Register the receiver in your onResume():
registerReceiver(onBroadcast, new IntentFilter("mymessage"));
Be sure to unregister in onPause():
unregisterReceiver(onBroadcast);
In your Service, you can post the message to the Application, which will be heard by your Activity:
getApplicationContext().sendBroadcast(new Intent("mymessage"));
If you need to, you can add data to the Intent's bundle to pass to your Activity as well.
my suggestion to you is, create a handler for the UI part which updates the text field or UI components.
Secondly, have notifications from the service to the activity by way of interface class.

Android from receiver to activity

I'm just getting into Android development, and I have a question about communicating between a receiver class and an activity class. I'm very new to JAVA and Android so I hope I don't sound too stupid. I'm developing an application where I intercept an SMS message and then based on various elements of that SMS I might delete it once it's been saved to the inbox. I have a receiver class that intercepts the txt message, and I am also able to delete messages from my inbox with code in the activity class using a button at the moment. The problem I have is communicating between the receiver class and the activity class where the code to delete a message resides. I tried putting that code directly into the receiver class but as I'm sure most of you already know the BroadcastReceiver class doesn't seem to support what I need to delete messages. I've been searching for an answer to this for a while, but haven't been able to find anything. Honestly I'm not sure I know enough about JAVA and Android to even recognize a solution if I saw it.
If you need to complete a job without an interface look into creating a Service, if you need user interface just start an Activity
You can use the Context parameter of the onReceive method of the receiver to start a new service/activity
You can use Extras to pass params between context. So you can put as extra the message id or entire message and pass it to your service/activity and deal it there.
You could implement the handling messages logic using an IntentService. When your receiver gets the new incomming message, start the IntentService passing an intent with the message data.
Receiver
onReceive(Context context, Intent intent) {
//Setup Intent
Intent i = new Intent(context, MyIntentService.class);
i.setAction(MyIntentService.HANDLE_MESSAGE);
//Pass data to intent
i.putExtra(MyIntentService.MESSAGE_DATA, data);
//Start Intent Service
context.startService(i);
}
MyIntentService
onHandleIntent(Intent i){
String action = i.getAction();
if(action != null && action.equals(MyIntentService.HANDLE_MESSAGE){
//Get data and implement message logic
}
}
Hope it helps.

Categories

Resources