My app has 3 or 4 async tasks, two of which get data from an sqlite database and create intents to send it to a receiver in the main activity. It all works fine - until I close the app and then restart it. The data is then not received correctly. After a lot of experimentation I discovered that if, after closing the app normally, I 'force stop' it, it works fine again - until the next time I run the task and again close the app. This behaviour doesn't show itself normally when running on the debugger. However, if I start the app on the device (rather than via Android Studio) and then attach the debugger, I can see quite clearly that the receiver is receiving two copies of the broadcast each time, instead of only one. One copy is correct, the other contains rubbish data. I have addded extra lines which show that the task ID is the same in each case.
The sending intent looks like this
private void sendRoads(ArrayList<RedRoad> roadsChunk)
{
ArrayList<RedRoad> theseRoads = new ArrayList<>(roadsChunk);
Intent mapIntent = new Intent("newRoads");
mapIntent.putParcelableArrayListExtra("newRoads", theseRoads);
mapIntent.putExtra("chunkIndex",cIndex++);
int threadID = android.os.Process.getThreadPriority(android.os.Process.myTid());
mapIntent.putExtra("threadID",threadID);
LocalBroadcastManager.getInstance(ctx).sendBroadcast(mapIntent);
// get ready for next group while we show these
roadsChunk.clear();
}
In order to try to solve this I have added extra lines to onDestroy:
@Override
public void onDestroy() {
super.onDestroy();
if (roadCreation!=null)
roadCreation.cancel(true);
if (parseKmlFile != null)
parseKmlFile.cancel(true);
Intent serviceIntent = new Intent(getApplicationContext(), LocationService.class);
stopService(serviceIntent);
}
but that appears to have made no difference (the two classes named are the two which use the method above. As you can see, there is also a service involved but I can tell by other means that it is stopping correctly).
I have tried to catch the erroneous broadcasts and ignore any action on them, but they still mess up the correct data.
I have two test devices; one sdk 26 (Oreo) and one 29 (Q); the latter is showing this problem evry time, the former only occasionally.