I have two apps. The first app launches the second app and should stop the second app after a time interval (currently 10 seconds) and then relaunch the app. Here is the code I have so far:
package com.example.launch
import android.content.ActivityNotFoundException
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onResume() {
super.onResume()
val launchIntent = packageManager.getLaunchIntentForPackage("com.example.secondapp")
while (true) {
if (launchIntent != null) {
try {
startActivityForResult(launchIntent, 1)
Log.d("", "Launching com.example.secondapp")
} catch (e: ActivityNotFoundException) {
Log.d("", "Failed to launch com.example.secondapp")
}
} else {
Log.d("", "Intent is null value.")
}
Thread.sleep(10000)
finishActivity(1)
}
}
}
On my android phone (Galaxy A12) the first app launches the second app but doesn't stop it. Here is some typical output from the first app.
2022-10-28 00:17:58.127 21240-21240/com.example.launch D/: Launching com.example.secondapp
2022-10-28 00:18:08.140 21240-21240/com.example.launch D/: Launching com.example.secondapp
2022-10-28 00:18:18.150 21240-21240/com.example.launch D/: Launching com.example.secondapp
So it seems from the output that the first app believes it is successfully launching the second app every 10 seconds. This doesn't correspond with what I am seeing on the phone or in the log for the second app which is continuing to run without being stopped or relaunched.
Where am I going wrong? How can I fix this?