使用AndroidKotlin从另一个应用程序自动打开应用程序

a64a0gku  于 2023-08-01  发布在  Android
关注(0)|答案(1)|浏览(138)

我想在特定时间从另一个应用程序自动打开一个/多个应用程序。
我尝试下面的代码打开一个特定的应用程序。但它不起作用。

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val openTimeMillis =
            System.currentTimeMillis() + (6 * 1000)  milliseconds
        scheduleAppOpenAndClose(this, openTimeMillis)
    }

    fun scheduleAppOpenAndClose(context: Context, openTimeMillis: Long) {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

        val openIntent = Intent(context, AppOpenReceiver::class.java)
        val pendingOpenIntent = PendingIntent.getBroadcast(
            context,
            0,
            openIntent,
            PendingIntent.FLAG_IMMUTABLE,
        )
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, openTimeMillis, pendingOpenIntent)
    }
}

字符串

*AppOpenReceiver.kt

class AppOpenReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, p1: Intent?) {
        val launchIntent = context!!.packageManager.getLaunchIntentForPackage("com.android.chrome") // Replace with your app's package name
        launchIntent?.let {
            it.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(it)
        }
    }
}


我期待在6秒后打开Chrome应用程序

3yhwsihp

3yhwsihp1#

您的AndroidManifest.xml中是否指定了接收方

<receiver android:name="YourReceiver"
        android:exported="true">
    </receiver>

字符串
像这样

相关问题