I have an Activity
with a TextView
called textView
. Within the activity there is a function void changeText()
which changes the text of textView
. This function can be called be pressing a Button
in the activity. Another way to call this function should be using an action of a notification (NotificationCompat.Builder.addAction
). When the action from the notification is invoked I don't want the activity to show up on the screen. I rather want the activity to invoke void changeText()
in silence (in the background). When the user enters my app the next time (and it is still alive) he should see the changed text. How can this be implemented?
Change text of a TextView using a notification action without opening the app
961 views Asked by principal-ideal-domain At
3
There are 3 answers
0
On
Try looking into SharedPreferences. You can save the text you want to display in a key-value pair, then load it and display it in the TextView
in your onCreate()
or onResume()
method.
3
On
NOTE: This solution will only work if the application is running in the background, if you want to do it while the application isn't running on the background you can use SharedPreferences
There are few ways to do this, most simply and good one is to simply store a static string inside the activity and when you create/restore to that activity you update the text:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.lang.Override;
public class TextActivity extends Activity
{
private static String mText;
public static void setText(String text) { mText = text; }
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView textView = (TextView)findViewById(R.id.textView);
if (mText != null)
textView.setText(mText);
}
}
Now when you receive the notification you update the text like this:
TextActivity.setText("Blah blah");
if you don't want activity show up on screen when clicks on button, you should use PendingIntent.getBroadcast() or PendingIntent.getService() and save in SharedPreferences as @Ido said
You can create a broadcast receiver in a new file called YourReceiver.java
And inside AndroidManifest.xml you must declare your receiver
now you can create the PendingIntent to put on your notification action button
I hope this can help you.
More info:
Tutorial BroadcastReceiver
http://developer.android.com/reference/android/app/PendingIntent.html