This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Android marshmallow request permission?
(26 answers)
Closed 12 months ago.
I'm trying to figure out permission in android. I have written a code that allows you to access the gallery with images. I didn't add any permission in the manifest. But from the app, I can access the gallery, although I shouldn't have (tried on an emulator and on a physical device).
Then I tried to do the same for a phone call. Here without <uses-permission android:name="android.permission.CALL_PHONE" /> an exception is thrown.
Can't figure out why I can access the gallery
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import ru.artrostudio.testgalery.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var uri: Uri
private lateinit var mBinding:ActivityMainBinding
var resultLauncher =registerForActivityResult(
ActivityResultContracts.GetContent(),
ActivityResultCallback {
println("${it.toString()}")
uri=it
mBinding.imageView.setImageURI(uri)
}
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView( mBinding.root)
mBinding.button.setOnClickListener {
resultLauncher.launch("image/*")
}
mBinding.button2.setOnClickListener { call() }
}
private fun call()
{
var tel="tel:0000000"
var intent=Intent(Intent.ACTION_CALL)
intent.data=Uri.parse(tel)
startActivity(intent)
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.TestGalery">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Related
I'm getting crazy while trying to make an app that will
kill specific other app
clear the killed app cache
restart the killed app again
for Android TV 10
lets call this app "the killer app"
i'm testing this app in android x86 emulator inside the android studio
i successed to kill the app but the app won't run even i enabled permissions for the killer app
thats the code i wrote:
package com.deliadsolutions.cachekillerstarter
import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
/**
* Loads [MainFragment].
*/
class MainActivity : FragmentActivity()
{
final var hotpackagename= "il.net.hot.hot"
fun startNewActivity(context: Context, packageName: String)
{
var intent = context.packageManager.getLaunchIntentForPackage(packageName)
if (intent == null) {
// Bring user to the market or let them choose an app?
intent = Intent(Intent.ACTION_VIEW)
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
// Toast.makeText(this, .cacheDir.path.toString(), Toast.LENGTH_SHORT).show()
val am = getSystemService(ACTIVITY_SERVICE) as ActivityManager
am.killBackgroundProcesses(hotpackagename)
this.cacheDir.deleteRecursively()
// var intent = this.packageManager.getLaunchIntentForPackage(hotpackagename)
// this.startActivity(intent)
//val launchIntent = packageManager.getLaunchIntentForPackage(hotpackagename)
//startActivity(launchIntent)`
val ctx: Context = this // or you can replace **'this'** with your **ActivityName.this**
try {
val i = ctx.packageManager.getLaunchIntentForPackage(hotpackagename)
ctx.startActivity(i)
} catch (e: Exception)
{
// TODO Anerated catch block
}
val intent = Intent(Intent.ACTION_MAIN, null)
intent.addCategory(Intent.CATEGORY_LAUNCHER)
val cn = ComponentName()
intent.component = cn
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
this.finishAffinity()
}
}
none of these app run methods starting the app
this is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature
android:name="android.hardware.touchscreen"
android:required="false" />
<uses-feature
android:name="android.software.leanback"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.Cachekillerstarter" >
<activity
android:name=".MainActivity"
android:banner="#drawable/app_icon_your_company"
android:exported="true"
android:icon="#drawable/app_icon_your_company"
android:label="#string/title_activity_main"
android:logo="#drawable/app_icon_your_company"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DetailsActivity"
android:exported="false" />
<activity
android:name=".PlaybackActivity"
android:exported="false" />
<activity
android:name=".BrowseErrorActivity"
android:exported="false" />
</application>
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.CLEAR_APP_CACHE"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
</manifest>
I have two activities, QuizQuestions, and MainActivity2. When I set up QuizQuestions in the Manifest intent filter the app opens and launches fine. However when I set up my app to open with MainActivity2 it fails to initialize at all. I have looked at the files side by side and I cannot find what the difference in them is to see why one would launch and the other wont.
I am brand new to Kotlin so I am sure it is something very obvious that I am missing. Any help is greatly appreciated.
Thank you.
Here is my manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.crazywkids.officequiz">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.OfficeQuiz">
<activity
android:name=".QuizQuestions"
android:exported="true"
/>
<activity
android:name=".MainActivity2"
android:exported="true"
android:theme="#style/NoActionBarTheme"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Here is MainActivity2
package com.crazywkids.officequiz
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
val beginBtn = findViewById<Button>(R.id.beginBtn)
beginBtn.setOnClickListener {
val intent = Intent(this, QuizQuestions::class.java)
startActivity(intent)
}
}
}
Here is QuizQuestions
package com.crazywkids.officequiz
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class QuizQuestions : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quiz_questions)
val question=Constants.getQuestions()
Log.i("Question Size", "${question.size}")
}
}
I have already searched for the problem that my huawei p30 lite doesn't discover other bluetooth devices. I tried it with an onther device and it worked but I don't get it why it doesn't work on my huawei p30 lite.
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notfallapp">
<uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#drawable/notfallapplogo"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.DayNight.NoActionBar">
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".menubar.MapActivity"
android:label="#string/title_activity_map"></activity>
<activity
android:name=".Login.LoginActivity"
android:screenOrientation="portrait"></activity>
<activity
android:name=".Login.SignUpActivity"
android:screenOrientation="portrait"></activity>
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".menubar.contact.ContactActivity"
android:screenOrientation="portrait"></activity>
<activity
android:name=".menubar.contact.AddContactActivity"
android:screenOrientation="portrait" />
<activity
android:name=".menubar.AlarmsActivity"
android:screenOrientation="portrait"></activity>
<activity
android:name=".menubar.SettingsActivity"
android:screenOrientation="portrait"></activity>
<activity
android:name=".alarm.CallAlarmActivity"
android:screenOrientation="portrait"
android:persistent="true"/>
<activity
android:name=".alarm.AlarmCanceledActivity"
android:screenOrientation="portrait" />
<activity
android:name=".alarm.AlarmSuccesfulActivity"
android:screenOrientation="portrait" />
<activity android:name=".menubar.ChangeProfilActivity"></activity>
<activity android:name=".connectBracelet.AddBraceletActivity"
android:screenOrientation="portrait">
</activity>
<activity android:name=".menubar.ChangeProfilActivity">
</activity>
</application>
</manifest>
AddBraceletActivity.kt
package com.example.notfallapp.connectBracelet
import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.notfallapp.MainActivity
import com.example.notfallapp.R
import com.example.notfallapp.interfaces.ICreatingOnClickListener
class AddBraceletActivity : Activity(), ICreatingOnClickListener {
private lateinit var btnSos: Button
private lateinit var btnHome: ImageButton
private lateinit var btnContact: ImageButton
private lateinit var btnAlarms: ImageButton
private lateinit var btnMap: ImageButton
private lateinit var btnSettings: ImageButton
private lateinit var btnRetrySearching: Button
private lateinit var btnCancel: Button
private lateinit var tvConnectBracelet: TextView
private lateinit var lvDevices: ListView
private lateinit var builder: AlertDialog.Builder
private var bAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
private lateinit var mReceiver: BroadcastReceiver
private var context = this
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_bracelet)
configureButtons()
initComponents()
btnCancel.setOnClickListener() {
Log.d("ButtonCancel", "Cancel Button was clicked in AddBraceletActivity")
sureDialog()
val alert = builder.create()
alert.show()
}
btnRetrySearching.setOnClickListener() {
Log.d("ButtonSearch", "Search Button was clicked in AddBraceletActivity")
searchDevices()
}
searchDevices()
}
private fun configureButtons() {
// SOS Button
btnSos = findViewById(R.id.btn_sos)
// Button bar
btnHome = findViewById(R.id.btnHome)
btnAlarms = findViewById(R.id.btnAlarms)
btnContact = findViewById(R.id.btnContact)
btnMap = findViewById(R.id.btnMap)
btnSettings = findViewById(R.id.btnSettings)
createOnClickListener(this, btnSos, btnHome, btnAlarms, btnContact, btnMap, btnSettings)
}
private fun initComponents() {
btnRetrySearching = findViewById(R.id.btn_retry_searching)
btnCancel = findViewById(R.id.btn_cancel_searching_device)
tvConnectBracelet = findViewById(R.id.tvConnectBracelet)
lvDevices = findViewById(R.id.lvDevices)
builder = AlertDialog.Builder(this)
mReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
System.out.println("Hello 2")
val action = intent.action
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED == action) {
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND == action) {
//bluetooth device found
val device =
intent.getParcelableExtra<Parcelable>(BluetoothDevice.EXTRA_DEVICE) as BluetoothDevice
val toast = Toast.makeText(context, "Found device " + device.name, Toast.LENGTH_LONG)
toast.show()
}
}
}
}
private fun searchDevices() {
//TODO search for Bluetooth devices.
Log.d("SearchDevices", "SearchDevices was called in AddBraceletActivity")
if (bAdapter == null) {
tvConnectBracelet.setError(getResources().getString(R.string.deviceNotSupportBluetooth))
return;
}
if (!bAdapter.isEnabled) {
val eintent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivity(eintent)
}
val discoverableIntent: Intent = Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).apply {
putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300)
}
startActivity(discoverableIntent)
if (bAdapter.isDiscovering){
bAdapter.cancelDiscovery()
}
/*val pairedDevices = bAdapter.bondedDevices
if (pairedDevices.size > 0) {
// There are paired devices. Get the name and address of each paired device.
for (device in pairedDevices) {
System.out.println(device.address)
}
}*/
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.i("info", "No fine location permissions")
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
1)
}
bAdapter.startDiscovery()
val onFoundFilter = IntentFilter(BluetoothDevice.ACTION_FOUND)
onFoundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
onFoundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
registerReceiver(mReceiver, onFoundFilter)
}
override fun onDestroy() {
bAdapter.cancelDiscovery()
unregisterReceiver(mReceiver);
super.onDestroy();
}
private fun sureDialog() {
builder.setTitle(getResources().getString(R.string.confirm))
builder.setMessage(getResources().getString(R.string.sureStopSearching))
builder.setPositiveButton(getResources().getString(R.string.Yes)) { dialog, which ->
var intent = Intent(this, MainActivity::class.java)
startActivity(intent)
dialog.dismiss()
}
builder.setNegativeButton(getResources().getString(R.string.No)) {dialog, which ->
dialog.dismiss()
}
}
}
These are my files where I have the permissions and where I scan for bluetooth devices.
Thank you very much for help!
Hello I solved my problem by reinstall my device to the base settings.
I apologize for my English.
I have a problem with redirecting to a subpage of Google results, SMS to WebView Android applications.
Example: The page with the address https://siteadress.pl/category in the Google results opens the WebView application and shows the homepage (https://siteadress.pl/)
LOOK PICTURE
Example: A page with the exact product https://siteadress.pl/shop/productxyz in Google results also opens the WebView application and shows the homepage. Why?
The link (https://siteadress.pl/shop/productxyz) from the sms message also opens the WebView application and shows the main page.
I want to point to the exact page of the application in WebView, not the homepage. :(
My AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pl.APP">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="APP"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="asset_statements"
android:resource="#string/asset_statements" />
<activity
android:name=".SplashScreen"
android:launchMode="singleTop"
android:noHistory="true"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.shortcuts"
android:resource="#xml/shortcuts" />
</activity>
<activity android:name=".ContactActivity" />
<activity android:name=".CategoryActivity" />
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="https"
android:host="siteadress.pl" />
</intent-filter>
</activity>
</application>
</manifest>
My MainActivity.xml
package pl.APP
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.webkit.URLUtil
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webView.webViewClient = MyWebViewClient()
webView.loadUrl("https://siteadress.pl/")
webView.settings.javaScriptEnabled = true
}
override fun onBackPressed() {
if (webView.canGoBack()) {
webView.goBack()
} else {
super.onBackPressed()
}
}
inner class MyWebViewClient : WebViewClient()
{
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean
{
if(URLUtil.isNetworkUrl(url))
{
return false
}
try
{
val shareIntent= Intent()
shareIntent.action=Intent.ACTION_VIEW
shareIntent.data= Uri.parse(url)
startActivity(shareIntent)
}
catch(e: ActivityNotFoundException)
{
Toast.makeText(this#MainActivity, "Appropriate app not found", Toast.LENGTH_LONG).show()
Log.e("AndroidRide",e.toString())
}
return true
}
#RequiresApi(Build.VERSION_CODES.N)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean
{
val url=request?.url.toString()
if(URLUtil.isNetworkUrl(url))
{
return false
}
try
{
val shareIntent= Intent()
shareIntent.action=Intent.ACTION_VIEW
shareIntent.data= Uri.parse(url)
startActivity(shareIntent)
}
catch(e: ActivityNotFoundException)
{
Toast.makeText(this#MainActivity, "Appropriate app not found", Toast.LENGTH_LONG).show()
Log.e("AndroidRide",e.toString())
}
return true
}
}
}
Thanks for help :)
The solution is you need to handle app link first, get the correct link and then load that link into your WeView:
Uri data = getIntent().getData();
if (data != null) {
String url = data.toString();
webView.loadUrl(url);
} else {
webView.loadUrl("https://siteadress.pl/");
}
Done! This version in "Kotlin" work:
val url = intent.data.toString()
if (URLUtil.isValidUrl(url)) {
webView.loadUrl(url)
} else {
webView.loadUrl("https://siteadress.pl/")
}
Thanks for help :) ufff
There are quite a few examples of using BOOT_COMPLETED to start an application when the device boots..
I have attempted to use these example against my Flutter application. Having it start the App. This is for a simply signage app that shows images. Basically similar to a picture frame.
In the example code below, the application is compiling, however, when I reboot a simulator, for example, the code does not appear to have any effect.
My guess is that I am not calling the right code to actually start the application.. I am not a Android developer, so am having issues figuring what is exactly going on.
Manifest follows..
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="au.net.digitall.cmplayer">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name="io.flutter.app.FlutterApplication"
android:label="cm_player"
android:icon="#mipmap/ic_launcher"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/cmTheme2"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver
android:enabled="true"
android:name=".StartCmPlayerServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
Then the StartCmPlayerServiceAtBootReceiver class to start the APP..
package au.net.digitall.cmplayer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class StartCmPlayerServiceAtBootReceiver extends BroadcastReceiver {
private static final String TAG = StartCmPlayerServiceAtBootReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "BOOT detected");
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, MainActivity.class);
context.startService(serviceIntent);
}
}
}
This all compiles and runs, but nothing happens on reboot.
Appreciate the help..
Thank to very much to Mike M.
His suggestion and pointing at the other android based discussion gave me enough info to archive autostart on boot. The code change to the above example follows..
In the StartCmPlayerServiceAtBootReceiver class,
Change to
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent mIntent = new Intent(context, MainActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mIntent);
}
}
Thanks again, and I hope other flutter devs find this useful.
Create receiver class on kotlin path project_name/android/app/src/main/kotlin/com/example/app/
package com.example.app
import android.content.BroadcastReceiver
import android.content.Context;
import android.content.Intent;
class BootReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
val i = Intent(context, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(i)
}
}
}
Add permission on your manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Add receiver tag inside application tag on your manifest
<receiver
android:enabled="true"
android:exported="true"
android:name="com.example.app.BootReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Add code to open your app after booting was completed on your MainActivity.kt, you can find it on project_name/android/app/src/main/kotlin/com/example/app/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var REQUEST_OVERLAY_PERMISSIONS = 100
if (!Settings.canDrawOverlays(getApplicationContext())) {
val myIntent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
val uri: Uri = Uri.fromParts("package", getPackageName(), null)
myIntent.setData(uri)
startActivityForResult(myIntent, REQUEST_OVERLAY_PERMISSIONS)
return
}
}
don't forget to import this code below on your MainActivity.kt because you need Bundle and Settings package
import android.os.Bundle
import android.provider.Settings
Works on my flutter app, tested on android 11.