I have two applications.
One app has the Activity and another one is a background service.
I can able to access the service app from my activity app using implicit intent filters.
I need to receive a result from the service.
For ex:
From activity app, i am going to start the service and send a data.
In the service app, i need to receive the data and do some inspections and need to return to the activity app as modified result.
I can able to send by putExtra and can able to retrieve it in the service by getExtra. I need to return a value from service and receive it in activity app.
PS: The thing i needed is, the same way what we do with finish() and onActivityResult() with the Activity results.
Thanks in advance to you masters...
First add a class like this:
package com.test.context; //For example
public class MyContext extends Application
{
//Here you define the attributes to share through the application
// with setters and getters
}
and in the AndroidManifest.xml, add the path of the class,
in the example is com.test.context so:
<application android:name="com.test.context.MyContext"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name">
Then in your code you can do some like this:
MyContext ctx = (MyContext)getApplication();
And you will be able to share data in all the app, btw activities and services, i did it this way in a Tasker , and works fine.
Why do you want to communicate through intent while there is a perfectly working binder protocol.
http://developer.android.com/guide/topics/fundamentals/bound-services.html
If an activity starts a service with 'bindService()' then the service will run until the activity calls 'unbindService()'.
Related
I have two activities, when I open Activity2, the Activity1 won't be closed. In Activity1 I have a handle that post a code (handler.postDelayed()), when this code run I need my Activity2 be notified in order to execute a other code too.
My question is: How can I send this message to Activity2 without reopening it.
I tried use an Intent with a specific action and catch it in onNewIntent() in Activity2; it works but the problem is that this reopen my Activity2. And I can't save the data in SharedPrefs cause my postDelayed() have no fix time, then I'd have to be checking all the time.
Does anyone know how I can send this message when my postDelayed() runs and how I catch it in Activity2 without reopening it? Please if possible post a example or a link to one.
Really thanks...
It was a simple solutions, like said #njzk2, was only add
<activity ..
android:launchMode= "singleInstance" />
or
<activity ..
android:launchMode= "singleTask" />
(both works).
Thanks
You shouldn't be using an Activity to handle long-running code, you should probably look into creating an IntentService to handle your background code. The IntentService can broadcast a new Intent when it is finished running the code. Have your first Activity start the Service, then instantiate a BroadcastReceiver in your second Activity to listen for updates from the Service.
Sending an broadcast Intent doesn't start or resume an Activity.
The BroadcastReceiver for an Activity receives and processes
Intent objects even when your app is in the background, but doesn't
force your app to the foreground.
I have an Activity and assume that has been launched. When the other application use startActivity method to start my Activity, my Activity will show and run the onResume Method, but I can't find any way to get the intent which is used in startActivity method by the other application. I want to get the extra data in the intent. How can I do?
EDIT
My Activity is singleTask, and I want to get the startActivity intents form other applications. I think it is not associate with filters.
Have you tried using getIntent() ?
Then you can do:
this.getIntent().getExtras();
After that if you need new intents just override the onNewIntent function in your activity.
I simply say an example. When we need to share something. We click share button which shows a list of app by which we can share our things.
So, if you want to make that kind of app which can receive other app data then you need make your activity capable of receiving that data. In order to receive implicit intents, you must include the CATEGORY_DEFAULT category in the intent filter in manifest.
Below this link you will get some more information : http://developer.android.com/training/basics/intents/filters.html
I have a Main-Activity which displays several spinners.
With a Toggle-Button in the Main-Activity I start a service which collects GPS-Data in background that measures the distance and sets some other variables.
When I stop the service with another click on the Toggle-Button in the Main-Activity, I stop the service, so the onDestroy() command is executed in the Service.
Within onDestroy in the Service, I want to submit the variables from the service to the already opened Main-Activity.
I tried that so far without success in the service:
Intent intent = new Intent(this, Main.class);
Bundle b = new Bundle();
Test = 2222;
b.putInt("Test", Test);
intent.putExtras(b);
I do not use the "startActivity(intent);", cause the activity that should the data send to is already open...the Main-Activity.
And on the side of the Main-Activity:
Bundle b = getIntent().getExtras();
if (b != null){
Test = b.getInt("Test");
}
else{
//..oops!
Toast.makeText(Main.this, "Oops...Nothing from service! :(", Toast.LENGTH_SHORT).show();
}
I never get data from the service.
I am trying this cause I need to start the service from the Main-Activity, from the Main activity the user stops the service and gets the values from it, then the Main-Activity should transmit the values from the service AND from the selected spinner values from itself to another activity.
I am trying that now for days and I also find some hints here, but nothing worked for me so far.
Someone any ideas?
Do I have to use a Broadcast-Receiver?
Whats the correct way to do this?
Before destroying the service store the data in shared preference and access it in the main activity
I don't know if this is the best way, but just have the Service you created update a static pojo. If the activity is already open then you could just set a timer to poll a the static pojo from the Activity to see if something has changed through an AsyncTask. When something has been updated in the pojo the AsyncTask can tell the Activity to update the UI accordingly. Then you don't have to play around with silly bundles. Also if your worried about your data getting lost you could always use SQLite. Hope this helps.
You need a broadcast receiver in main activity to get the data.
How can I send data from a Service to an Activity? Broadcast receiver? Handlers? Intent? I have several Strings in particular that I would like to send from Service to an Activity, so that I can then display some View to the user.
getApplication().startActivity(new Intent()) ?
Since both Activity & Service is in same application. Instead of going for Service Binder IPC, try implementing register callBack mechanism. Try follow below step.
-> Make a static class which extends from class Application to make quick reference anywhere in your application.
-> Register a callBack from Activity to this application class.
-> Post event from your service to the application class and let Application class deliver the event to all register callBacks.
As #justin-shield mentioned the best way is to use some form of IPC. I don't think you need to use AIDL, however. You can see another answer I gave to a similar question that outlines the basic steps to register Handlers and Messengers in your Activity and your Service.
I think all your answers are way more complex than what I need. I think I have come up with a rather simple solution (psuedo-code):
Service:
Intent i = new Intent(this,Activity.class);
i.putExtra(name,value);
startActivity(i);
Activty:
private Intent intent;
private String s1;
from the onCreate(Bundle savedInstanceState)
{
super(savedInstanceState);
intent = this.getIntent(); //Gets the intent that started this Activity.
s1=intent.getExtras().getString(name);
}
Would I use same code in onStart() ? What about onResume() ? onRestart() ? Lastly, I only want to send to the Activity some data to publish via some View objects, I don't need any communication going back to the Service.
I have a simple question to solve, but I am not sure how to do it.
I have a class that extends Service that runs a thread looking for a TCP connection. If one comes in, it read an input message.
If the input message is "START", I start an activity, in this fashion:
Intent dialogIntent = new Intent(getBaseContext(), VoIPCall.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
dialogIntent.putExtra("inetAddress", clientSocket.getInetAddress());
getApplication().startActivity(dialogIntent);
While this activity is running, the Service keeps running. At some point I may reserve a "STOP". I would like to call a method in the previously created Activity but I am not sure how to interact with it.
I do not want to use a static method. How can I please do that?
Thank you very much,
EDIT: I changed my code to this:
Intent dialogIntent = new Intent("com.voip.rudy.START_CALL");
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
dialogIntent.putExtra("inetAddress", clientSocket.getInetAddress());
getApplication().startActivity(dialogIntent);
And in the manifest:
<activity android:name=".VoIPCall">
<intent-filter>
<action android:name="com.voip.rudy.START_CALL" />
<action android:name="com.voip.rudy.STOP_CALL" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<category android:name="android.intent.category.DEFAULT" /> was required to avoid having it crash.
EDIT:
The solution given has fixed my issue but I wanted to actually act on member variables on that class, that are previously initialized. Say I call the constructor, then I would like to go back into this activity and act on the member variables.
The member variables are not initialized when I call one action after another, it seems to create a new activity somehow. Would there be anyway to act on the same activity, and keep the objects intact please?
James
Add the Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT flags to your intent and call startActivity with a new action or a special extra that can identify the intent.
In the activity, write a method called :
private void handleIntent(Intent intent) {
}
call this from onCreate (or onResume) using:
handleIntent(getIntent());
and also write:
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
There are a few ways to do it, really depends on the overall structure of your application. All can work. Off the top of my head these are the methods that come to mind
1) Create a custom intent and have the activity or service react to it when the otehr sends it
2) Instead of the service, setup the logic looking for the tcp connection as an async task within the dialog activity, when you have the tcp connection you could pass it off to the service to do its work
3) Take a look at the local service and remote service SDK examples and use the callback code as the basis for passing data back to the activity. You can also call through the interface back to the service.
4) Maybe even setup a broadcast receiver 'architecture'. This has the advantage of decoupling the user activity from the service entirely. You could put some of your application logic in a service in another process, or even in a process that runs at device boot.
I think any of the techniques would work. I'm guessing that the behavior you are seeing is related to the lifecycle of the activities within android and you might need to move some of your processing to the onResume/onPause or onStart/onStop methods. If you you find that your activity onCreate is not being called, but you now your activity is active, it might jsut be that an activity instance from a previous invocation is still alive in the system. If so, it is possible that the OS is using that instead of the new activity that you want. The best way to see if this is a problem is to put some "Log.d" calls at the beginning and end of all of the activity methods that you override. You will be able to tell what is happening by watching logcat. The technique that you use may also be dependent on how synchronous you want the activity's reaction to be with the TCP event. If you want completely async you can go with a standard broadcast, or a service callback with a message send. If you want synchronous then do it with a service callback. In case you haven't seen it this SDK link has a pretty good description of the activity lifecycle http://developer.android.com/reference/android/app/Activity.html