How to update textview text which is update in service class - android

I have developed an app with start, pause, resume and finish buttons.
It works properly in the activity using thread and handler.
If the user clicks on the start button a thread is started and displays textviewHH:MM:SS time and the rest of the buttons work correctly as well.
Problem:
If the activity goes to background then how do I update the textview time? I have made services for this task but, how do I take the response from services to UI?
Please, could you give me any idea of how to do it or any other possible solution?

You can create CustomBroadcast
Here is sample code.
Try this, it will work..
In YourService.Java
public static final String BROADCAST_ACTION = "com.example.tracking.updateprogress";
intent = new Intent(BROADCAST_ACTION);
sendBroadcast(intent);
In YourActivity.Java
registerReceiver(broadcastReceiver, new IntentFilter(YourService.BROADCAST_ACTION));
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Update Your UI here..
updateUI();
}
}
You can also pass data in Intent.

If you create a simple new Thread(new Runnable() {...}) within the Activity you can run UI manipulations with the runOnUiThread(new Runnable() { // your UI modify method }) Acitvity method. If the Activity go to the background the Thread is still running.

Related

Specify what classes I want my handler to run

I have a class with a handler in it and it works fine, but it then hits a class where I want the handler to stop if the timer has not already timed out. So if the handler reaches the end it should go to the Drunk class, if the user reaches the end of the app before the handler goes off, the handler should not go off. I have it going off at the end of the app but I don't want it too. It should stop once it hits the end of the app.
THANKS!
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run()
{
toDrunk();
}
},20000);
public void toDrunk(){
Intent i = new Intent(this, Drunk.class);
startActivity(i);
}
You need to remove that message from the handler when the activity is stopped. You can do that either by storing the runnable in some variable and then removing it using removeCallbacks or by posting the runnable with some token and then removing all messages with that token using removeCallbacksAndMessages.

IntentService runs in the background even after the onHandleIntent finishes

I'm building an application that has a widget and a button in the widget launches an IntentService.
The onHandleIntent() runs some code and then raises a toast through a handler.
After I click the button in the widget, I see the toast and I know that onHandleIntent finished.
But when I look in the background services I still see my app there.
As a user, I get very annoyed when apps always run on the background and wasting my precious RAM. My widget doesn't need to run in the background because my widget doesn't update ever (the update rate in the xml is 0).
So how come that the service is still running? How can I stop it?
IntentService code:
public class WidgetCheckService extends IntentService {
private int mAppWidgetId;
Handler mHandler = new Handler();
public SalaryWidgetCheckService(String name) {
super("laceService");
}
public SalaryWidgetCheckService() {
super("laceService");
}
#Override
protected void onHandleIntent(Intent intent) {
// Badass code
mHandler.post(new DisplayToast(getString(R.string.widget_service_check_in_success_toast_text).replace("LACE", lace)));
else mHandler.post(new DisplayToast(getString(R.string.widget_service_check_out_success_toast_text).replace("LACE", lace)));
}
private class DisplayToast implements Runnable{
String mText;
public DisplayToast(String text){
mText = text;
}
public void run(){
Toast.makeText(WidgetCheckService.this, mText, Toast.LENGTH_SHORT).show();
}
}
}
Thanks, Elad.
But when I look in the background services I still see my app there.
Your process is not automatically terminated when the service ends. Android will keep your process running until it needs to free up the RAM for other apps, just in case it happens to need to run something from your app again. This is no different than any other app on Android.

Updating UI from a service (using a handler?)

I am trying to update my UI in FirstActivity when I receive a notification but is confused by runOnUiThread , Runnable and Handler. Here is what I have: I am running FirstActivity and NotificationService. When NotificationService reeives a notification, it will update FirstActivity UI.
I also have another service AlarmService running.
First Activity
#Override
public void onResume() {
super.onResume();
//some other code for alarm service
}
NotificationService
//on receiving notification
private void showNotification(String text) {
//Get activity
Class<?> activityClass = null;
try {
activityClass = Class.forName("com.pakage.FirstActivity");
contextActivity = (Activity) activityClass.newInstance();
//Update UI on FirstActivity not working
contextActivity.runOnUiThread(new Runnable() {
public void run()
{
Looper.prepare();
TextView tv = (TextView ) contextActivity.findViewById(R.id.notifyTest);
Looper.loop();
}
});
} catch (Exception e) {
e.printStackTrace();
}
//Shows the notification
Notification n = new Notification();
//... etc
}
I keep getting looper.prepare error. Do I need to put extra codes in my FirstActivity?
My 1st instinct is that you should instead have the Activity bind to your service and handle the UI update on its side instead of the Service directly modifying the Activity.
See more info here:
http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
And an example here:
Example: Communication between Activity and Service using Messaging
I've always just had the service fire off a Broadcast and then in my Activity I have a BroadcastReciever listening for the Broadcast. It's an approach that is much simpler than the one you outlined above.
I have no idea why you are putting a Looper in
contextActivity.runOnUiThread(new Runnable() {
public void run()
{
Looper.prepare();
TextView tv = (TextView ) contextActivity.findViewById(R.id.notifyTest);
Looper.loop();
}
});
because the UI (main) thread already has a Looper/Handler etc..
Even if it did work Looper.loop() is going to block and since you are running it on the UI thread, it will block the UI thread which is not what you want.
What you really want to do is
contextActivity.runOnUiThread(new Runnable() {
public void run()
{
TextView tv = (TextView ) contextActivity.findViewById(R.id.notifyTest);
tv.setText("do something that must be on UI thread") // or whatever
}
});
You don't really need to do all this fancy stuff to get the Activity
activityClass = Class.forName("com.pakage.FirstActivity");
contextActivity = (Activity) activityClass.newInstance();
assuming the Service and Activity are both running in the same process you can just save a reference to the Activity but be careful to update the reference when the Activity gets destroyed.

Android Button Response Problem

hi all
since i am using a button and on the click of that button it connects to a Web Service.
But the problem is that when i press the button it does not showed me that it has been clicked and goes to connect to the internet and web service. after connecting it shows me the response that it has been clicked. in short the response of button is very slow. if that buton has some INternet connectvity in its Listener.
i know it has something to do with UI thread. but please friends guide me through this.
Thanks a bunch,
Put the following code in your class:
// Need handler for callbacks to UI Threads
// For background operations
final Handler mHandler = new Handler();
// Create Runnable for posting results
final Runnable mUpdateResults = new Runnable() {
public void run() {
// Do your task which needs to get done after webservice call is complete.
}
};
And for calling the webservice use the following code in button event:
new Thread() {
public void run() {
// Place the webservice call here.
mHandler.post(mUpdateResults);
}
}.start();
Actually what are you looking for is multithreading, all the webservice calls and network activities should go in separate thread.
After the thread start() call you can do what ever you want and would be done instantly without any delay (in your case showing that button pressed).
You have to use Handler for this background operation already ask on OS follow this link
progress dialog not showing in android?
You should write a class say MyWebService and extend it from AsyncTask. Perform the connect operation in its overridden doInBackground() method and update any UI changes in its onPostExecute() method.
Create a new Thread in the onClickListener that does the heavy work in the background. That way the UI thread will be able to update the state of the button:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
// Code that connects to web service goes here...
}
}).start();
});

How can I refresh the activity?

I want to refresh the activity as i want thatwithout firing any event some work gets performed and activity calls by itself. So, i want to know is there any option in android to refresh the activity by itself.
You can do this by yourself through a Handler on which you call postDelayed(..)
http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long)
Put this in your class:
private final Handler handler = new Handler();
make a function called: doTheAutoRefresh() that does:
private void doTheAutoRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
doRefreshingStuff(); // this is where you put your refresh code
doTheAutoRefresh();
}
}, 1000);
}
Call this function in your onCreate.
NOTE: this is the basic approach. consider stopping this after onPause has been called and to resume it after onResume. Look at the handler class to see how to remove.
You can create a thread and and call the refresh() with the task you want to refresh
for other questions I've pulled the most effective ways to do this are:
finish();startActivity(getIntent());
OR
// Refresh main activity upon close of dialog box
Intent refresh =new Intent(this, ActivityWeAreIn.class);
startActivity(refresh);
Note: this also works with Activity objects or from Fragments using getActivity()

Categories

Resources