Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Textview in an Activity with Local Service

I have an Activity with R.id.eventDistance and R.id.eventTime to display the distance & travel time based on current location. I calculate these values every 30 seconds using my Location Service class.

My question is: how do I update the TextView in Activity? I've tried looking up the question and found some possible solutions such as using a BroadcastReceiver and call TextView.setText() in the onReceive() method. I'm not sure how this is done. Am I supposed to pass in the Activity class like this:

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Intent i = new Intent(context, HomeActivity.class);
   }
} 

I'm not sure what to do after that. Any help is appreciated.

like image 396
Dao Lam Avatar asked Feb 25 '13 04:02

Dao Lam


People also ask

How change TextView text from another activity?

You have to use Intent to make action in another activity. textView. setText(btn_text);

How would you update the UI of an activity from a background service?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view, when user gets the data from intent service it will update.

What is SetText in Android Studio?

SetText(String, TextView+BufferType)Sets the text to be displayed using a string resource identifier.

How send data from service to activity in Android?

getInstance(getActivity()). registerReceiver( mMessageReceiver, new IntentFilter("GPSLocationUpdates")); By this way you can send message to an Activity. here mMessageReceiver is the class in that class you will perform what ever you want....


2 Answers

please see this flow.

1.in your LocationService class when you want to update UI. in your case it should be called every 30 seconds.

Intent i = new Intent("LOCATION_UPDATED");
i.putExtra("<Key>","text");

sendBroadcast(i);

2.in your UI (HomeActivity) class

in onCreate()

registerReceiver(uiUpdated, new IntentFilter("LOCATION_UPDATED"));

in class

private BroadcastReceiver uiUpdated= new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        TextView.setText(intent.getExtras().getString("<KEY>"))

    }
};

in onDestroy()

unregisterReceiver(uiUpdated);
like image 133
Jignesh Ansodariya Avatar answered Sep 18 '22 02:09

Jignesh Ansodariya


You should bind your Activity to your service so that they can directly communicate and message pass.

Ref

http://developer.android.com/guide/components/bound-services.html

like image 33
JoxTraex Avatar answered Sep 18 '22 02:09

JoxTraex