Android : textview resets every time i come back to the app

on Thursday, September 11, 2014


Im new in android development and I have to do an application that checks for the app running in foreground, and it should update a textview with the name of the apps. For the moment Im using a string, cause i cant reference a non final variable from the runnable inner class.


I have placed my code into a Runnable class into the oncreate method of my main activity, dont know if it is the right place to put it since I want to run that once, and then let the thread do his job with an infinite loop.


One of the several problems I found is when I run my application, every time i come back to the app, the textview is empty, then the thread begins to fill it with my string, but when i left the app and come back again, is empty.


How can i keep the contents of the textview?


I put my code here, thanks for the help.



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if (!bExecuted)
{
bExecuted = true;

setContentView(R.layout.activity_main);

final TextView myText = (TextView) this.findViewById(R.id.my_view);
final ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
final PackageManager pm = this.getPackageManager();

Runnable myRunnable = new Runnable() {
@Override
public void run() {

String foregroundTaskAppName = "";
String foregroundTaskAppNameOld = "";

while (true)
{
try
{
Thread.sleep(500);
// The first in the list of RunningTasks is always the foreground task.
RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);

String foregroundTaskPackageName = foregroundTaskInfo .topActivity.getPackageName();

PackageInfo foregroundAppPackageInfo;

foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);

foregroundTaskAppNameOld = foregroundTaskAppName;
foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

if (!foregroundTaskAppNameOld.equals(foregroundTaskAppName))
{
myText.post(new Runnable() {
@Override
public void run() {
String textOld = (String)myText.getText();
myText.setText(textOld + "hol\n");
}
});
}

} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};

Thread myThread = new Thread(myRunnable);
myThread.start();
}
}

0 comments:

Post a Comment