In my android application,I am getting data from internet and I refresh data in every minute.
So my question is:
When application is minimized, i want to inform the users that new data is available via notifications.
How can i do this?
use onUserLeaveHint() of Activity` because this method is called when an activity is about to go into the background as the result of user choice like by pressing Home key , menu key,search key or any incoming phone call.
So when this method is called then start your service for data notifaction because onUserLeaveHint() is called when your application is minimized.
Set your application in a way that the data receiving and sending is handled by a Service. From the service, on events of data send/receive, fire up notifications.
In your case, I think its best to use unbound services
Try this::
#Override
protected void onUserLeaveHint()
{
System.out.println("Home Button Pressed");
super.onUserLeaveHint();
}
Related
I don't know if this is possible, but I would like to do the next:
Imagine an app with 2 activities: MenuActivity and OtherPurposeActivity.
So, on the onCreate method of Menu I had run the Service. In the same Activity (Menu), I can easily "connect"(Edit: communicate) with this Service with no problems.
Then, I click the only button there is on MenuActivity, which starts OtherPurposeActivity. Here comes the question:
How can I connect to the Service I had run on MenuActivity? Is it possible? (I hadn't called stopService).
Thanks in advance.
Edit: Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
/* Execute service */
Log.d("SERVICE", "Launching service");
Intent msgIntent = new Intent(MenuActivity.this, ServerProcessingService.class);
msgIntent.setAction(ServerProcessingService.ACTION_STATUS);
startService(msgIntent);
/* Connection to the IntentService */
IntentFilter filter = new IntentFilter();
filter.addAction(ServerProcessingService.ACTION_STATUS);
//filter.addAction(ServerProcessingService.ACTION_CONTROL);
rcv = new ProgressReceiver();
registerReceiver(rcv, filter);
}
So I can handle the communication with the ProgressReceiver class. But, what if I open another activity, and this service still running? Can I access to it?
How can I connect to the Service I had run on MenuActivity?
Another activity that wants to communicate with the service can use exactly the same method as MenuActivity. startService() will only start the service if it is not already running, and then send the intent to onStartCommand() in all cases, so it is all right to call start service from multiple activities.
As a commenter pointed out, if your activity requires ongoing communication with a service, you should bind to it.
Is it possible? (I hadn't called stopService).
An IntentService will stop itself if it has no work to do, so it doesn't matter that you did not stop it explicitly. If the service needs to continue running, don't use an intent service.
To be on the same page I will describe briefly how I understood your dilemma.
You have an IntentService perfroming some operation which provides at the end some results. You are starting this process in one activity(asynchronously of course) and switch immediately to another one. Now, you are not sure whether service will finish the work before you switch to second Activity and result will be lost.
Basically, approach with BroadcastReceiver would be a good choice but if you won't register on time the data will be lost and service will end it's work. You could let the service to store the result before it ends, in DB, file or even in memory(depending on data type). When your second Activity start you can check if there is data waiting for you, if not you can wait for BroadcastReceiver to deliver it.
You could also use Otto library which is far more advanced solution than BroadcastReceiver. It allows to return to registered observer(Activity) the last result and what is more important it will allow your service to check if any observer received the message. If not you could only then store last result.
I'm so lost with all that workflow of notifications and services in Android. My sceneario is this:
I have an Android application that communicate to a MySQL database through a web-service using JSON-RPC. The data retrieved from the service will be displayed in the application.
The data will get updated over time, so the application needs to listen for changes of this and, if a change occur, show a notification and update the data displayed in the app.
To listen for changes I will need to run an "infinite"(until the app is destroyed or maybe until the app destroys it) thread that from time to time will call a method on th web-service which will return the changes since the last check.
UPDATE: Ok, I have been trying using Service and IntentService, but non of them fits my needs: a Service execute in the Main Thread, so If I perform an infinite loop there my app will freeze, IntentService has it's own worker thread but there is no comunication with the App, and I need it, or at least I need a way to know if the app is in foreground (in this case the notification will not popup but the data will be passed and updated) or in background (int this case the notification will pop up and on click it will direct the user to the app with the updated data)
#1 You can fire a broadcast message from your Service and define a Broadcast receiver in your Activity to receive this broadcast.
SEND BROADCAST-from Service
Intent i = new Intent("ALERT_CHANGE");
i.putExtra("DATA","News");
sendBroadcast(i);
RECEIVE BROADCAST-in Activity
registerReceiver(uiUpdated, new IntentFilter("ALERT_CHANGE"));
private BroadcastReceiver uiUpdated= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
String DATA = i.getStringExtra("Data");
txt.settext(DATA);
}
};
Ok, after a lot of testing and thanks to the info given here I finally found a way to handle with the issue, so I will share it here:
On the IntentService I have a public static AtomicBoolean to control the end of the loop and be able to stop the service.
Then to determine if the Activity is in foreground or not I use the method suggested here https://stackoverflow.com/a/5504711/3107765
With the difference that I use the static modifier there, so I can check it from the service.
if the activity is in foreground I send a broadcast as it was suggested here by Eu. Dr. otherwise I use a notification that once clicked will let the user to the activity.
I am creating an android service using this code:
var intent = Ti.Android.createServiceIntent({
url : 'service.js'
});
Ti.Android.startService(intent);
As you can see, this service is started only once, it is not called in an interval every X milliseconds. Now when the application is exited (not put to background) and started up again, I would like to retrieve the reference of the service and stop it if the user clicks the stop button. Is there any way of achieving this? Thank you
Stop a Service in app.js by
Identifying the stop button click event and call this to stop service
if(Ti.Android.isServiceRunning(intent){
Titanium.Android.stopService(intent);
}
I'm currently writing an app, what has an on-boot service. This service simply pops up a notification after a time, and update it in given periods with new info. Currently there's no need for any further battery saving, I just want the update sequence to work.
I've hit a problem tho. Created the boot BroadcastReceiver what then starts my Service. It it, I do the work via a Timer and a TimerTask. But as I saw, there's no easy way to check if the notification was deleted, and thus not try to update it, but re-create it.
What I want to do:
private Notification n;
NotifTask extends TimerTask {
public void run() {
if(n.exists){
// Update notification
}else{
n = Notification.Builder(context).[customize it].build();
}
}
}
And in the service's onStart, set up a timer what runs this task every 10 seconds.
Now, my question is: is there any way to do the "n.exists" part easily, without intents?
If you post a notification and this notification already exists, it will just get updated with the new information. If it doesn't exist it will be created. I don't think you need to do anything special to get the behaviour you want.
From the documentation for NotificationManager.notifiy():
Post a notification to be shown in the status bar. If a notification
with the same id has already been posted by your application and has
not yet been canceled, it will be replaced by the updated information.
My app has a chat screen to send and receive messages. Whenever a message is received a push notification comes in and shows the latest received message. This all works fine.
But when I get my push notification I would like the chat screen to refresh itself. I guess this would require knowing if the chat screen is currently visible or not. How can I do this from the onReceive() method of my BroadcastReceiver?
Here's a little pseudo code (in my BroadcastReceiver subclass):
public void onReceive(Context context, Intent intent)
{
if(currentlyVisibleActivity.getClass() == chatScreenActivity.class())
{
((chatScreenActivity)currentlyVisibleActivity).getMessages();
}
}
I would like to know how to get the currentlyVisibleActvity and make it call getMessages() if it's a chatScreenActivity.
I assume you are planning the following setup?
C2DM -> YourBroadcastReceiver -> somehow call #getMessages()
How about having the following components:
A BroadcastReceiver <for receiving C2DM push notifications>
An IntentService <for executing #getMessages()>
A ContentProvider <for storing the results of #getMessages()>
An Activity <for displaying the contents of ContentProvider>
Basically, C2DM triggers your receiver which calls #startService, triggering
your IntentService.
Your IntentService calls #getMessages() and stores the messages in your
ContentProvider.
Whenever a change is performed on the data in the ContentProvider you will
trigger ContentResolver#notifyChange().
If your Activity is showing and uses, for instance, a CursorAdapter to read
from the ContentProvider it will automatically refresh.
Sending a chat message would also store a row in the ContentProvider in this scenario - automatically updating the UI just as a received message.