I have a FragmentA..that is a list fragment,it loads a list of contacts and displays them similar to what a phonebook would do.Now if I click on a contact say "John Doe" the app will launch another app (Sim Tool Kit in my case) and also display the toast with his name and number for the user to use while using the STK. Once the user completes using the STK or navigates back to the App then the toast should disappear. But in my case the Toast still persists and in some cases even when I exit my app the toast will appear infinitely. How do I correct this? Below are snippets of my Code
list.setOnItemClickListener(new OnItemClickListener() {
@SuppressLint("RtlHardcoded")
@SuppressWarnings("deprecation")
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> h = (HashMap<String, String>) list.getAdapter().getItem(position);
String Name="",Number="";
Name = h.get(KEY_NAME);
Number = h.get(KEY_PHONENUMBER);
toast = Toast.makeText(context, "", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP|Gravity.RIGHT, 0, 0);
toast.setView(layout);
toast.cancel();
userNameText.setText(Name);
userNumberText.setText(Number);
PersistToast();
getActivity().startService(ServiceIntent);
try {
if (!ReceiverON) {
getActivity().registerReceiver(objReceiver, filter);
ReceiverON=true;
}
} catch (IllegalArgumentException illegalargumentexception) {
illegalargumentexception.printStackTrace();
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
The persist Toast method
private void PersistToast() {
long delay = 1000;
long period = 1000;
mDoTask = new TimerTask() {
@Override
public void run() {
toast.show();
}
};
mT.scheduleAtFixedRate(mDoTask, delay, period);
}
The Receiver
private class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
if (!(currentTask().equals("com.android.stk"))){
try {
if(toast != null) {
toast.cancel();
mDoTask.cancel();
}
} catch(Exception e) {
}
}
}
}
public String currentTask() {
return ((android.app.ActivityManager.RunningTaskInfo)((ActivityManager)context.getSystemService("activity")).getRunningTasks(1).get(0)).topActivity.getPackageName().trim();
}
The service pings the receiver periodically so that the receiver in turn checks to if the current Activity in front is the STK,if it is not then it cancels the toast and the timer task