Skip to content

Prevent CoGo‐built apps from stopping on Android 16 devices

Elissa-AppDevforAll edited this page Jul 23, 2026 · 1 revision

Some users report that apps built in CoGo repeatedly stop on devices running Android 16. This issue is a result of Android blocking background processes. To solve this problem, open the app’s project in CoGo, and add the following code to AndroidManifest.xml and MainActivity.

1. In AndroidManifest.xml, declare this permission:

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

2. In MainActivity, add this function:

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import android.widget.Toast

// Request to ignore battery optimizations to prevent the system from killing the app
@SuppressLint("BatteryLife")
private fun requestIgnoreBatteryOptimizations(context: Context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val intent = Intent()
        val packageName = context.packageName
        val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager

        // If the app is not exempted, request the exemption from the system
        if (!pm.isIgnoringBatteryOptimizations(packageName)) {
            intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
            intent.data = Uri.parse("package:$packageName")
            try {
                context.startActivity(intent)
                Toast.makeText(context, "Please allow the app to run in the background to prevent it from being closed.", Toast.LENGTH_LONG).show()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}

3. In MainActivity, call the function from onCreate:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // Call the battery optimization request function
    requestIgnoreBatteryOptimizations(this)

    // ... rest of your UI code ...
}

Clone this wiki locally