app was closed JobService not running periodically - android

I have a Jobservice that runs periodically every time.My activity only is to job start for running on the app.i can stop or destroy the app manually using UI and the JobService not running ,the jobservice why stop i don't know.i attached the my manifistfile and Jobdispatcher what i do something else?
dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(getActivity()));
Bundle myExtrasBundle = new Bundle();
myExtrasBundle.putString("some_key", "some_value");
if (myJob == null) {
myJob = dispatcher.newJobBuilder()
// the JobService that will be called
.setService(ReminderService.class)
// uniquely identifies the job
.setTag("my-unique-tag")
// one-off job
.setRecurring(true)
// don't persist past a device reboot
.setLifetime(Lifetime.FOREVER)
// start between 0 and 60 seconds from now
.setTrigger(Trigger.executionWindow(0, 60))
// don't overwrite an existing job with the same tag
.setReplaceCurrent(true)
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_LINEAR)
// constraints that need to be satisfied for the job to run
.setConstraints(
// only run on an unmetered network
Constraint.ON_ANY_NETWORK
)
.setExtras(myExtrasBundle)
.build();
dispatcher.mustSchedule(myJob);
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.vvsugar">
<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
<permission
android:name="${applicationId}.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application
android:name=".AppController"
android:hardwareAccelerated="true"
android:icon="#mipmap/ic_launcher"
android:installLocation="internalOnly"
android:label="#string/app_name"
android:largeHeap="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:icon,android:theme">
<meta-data
android:name="DATABASE"
android:value="vvsugae.db" />
<meta-data
android:name="VERSION"
android:value="1.45" />
<meta-data
android:name="QUERY_LOG"
android:value="true" />
<meta-data
android:name="DOMAIN_PACKAGE_NAME"
android:value="com.vvsugar.dbview" />
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
<activity
android:name=".activity.LoginActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.vvsugar.activity.ReminderService"
android:enabled="true"
android:exported="false"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.REBOOT"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
<activity android:name=".activity.DashBoardActivity" />
<activity android:name=".base.BaseActivity" />
<activity
android:name=".activity.MainActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:windowSoftInputMode="stateAlwaysHidden|adjustResize" />
<activity android:name=".uicomponent.imagepicker.activities.AlbumSelectActivity" />
<activity android:name=".uicomponent.imagepicker.activities.HelperActivity" />
<activity android:name=".uicomponent.imagepicker.activities.ImageSelectActivity" />
<activity
android:name=".adapters.PaymentsAdapter"
android:label="#string/title_activity_payments_adapter"
android:theme="#style/AppTheme.NoActionBar" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBwdtoapVVM-Yg4VIKNuFaH8f3GqN7pd98" />
<!--
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
-->
<meta-data
android:name="io.fabric.ApiKey"
android:value="eab11ffa174990145b21fef7ed3fd2ddcf6ca4c8" />
<activity android:name=".activity.ActiveWindow"></activity>
</application>
</manifest>

On your Job service return true on onStartJob
override fun onStartJob(jobParameters: JobParameters): Boolean {
return true
}
also override onStartCommand like this
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
return Service.START_STICKY
}
and for menifest write code like this
<service
android:name=".JobServiceEx"
android:permission="android.permission.BIND_JOB_SERVICE"/>
Your service will look like this for Kolin code
class JobServiceEx : JobService() {
var startTime: Long = 0
val workHandler = Handler()
var workRunnable: Runnable? = null
// Called by the Android system when it's time to run the job
override fun onStartJob(jobParameters: JobParameters): Boolean {
Log.d(TAG, "Job started!")
workRunnable = object : Runnable {
override fun run() {
val millis = System.currentTimeMillis() - startTime
var seconds = (millis / 1000).toInt()
val minutes = seconds / 60
seconds %= 60
var curTime = "$seconds"
Toast.makeText(baseContext, "Current Sec : $curTime", Toast.LENGTH_SHORT).show()
Log.e("TAG", "Current Time : $curTime")
workHandler.postDelayed(this, 1000)
}
}
workHandler.post(workRunnable)
return true
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
return Service.START_STICKY
}
// Called if the job was cancelled before being finished
override fun onStopJob(jobParameters: JobParameters): Boolean {
workHandler.removeCallbacks(workRunnable);
return false
}
companion object {
private val TAG = JobServiceEx::class.java.simpleName
}
}
and start and stop service like this
R.id.buttonStart -> {
/**
* start job service to test
*/
var componentName = ComponentName(this, JobServiceEx::class.java)
var jobInfo: JobInfo? = null
jobInfo = JobInfo.Builder(JOB_ID, componentName)
.setRequiresCharging(true)
.setMinimumLatency(1)
.setOverrideDeadline(1)
.build()
var jobScheduler = getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler
var resultCode = jobScheduler.schedule(jobInfo);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.e("TAG", "Job scheduled!");
} else {
Log.e("TAG", "Job not scheduled");
}
}
R.id.buttonStop -> {
/**
* stop job service to test
*/
val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
jobScheduler.cancel(JOB_ID)
}

Related

Screen not turning on when alarm manager is fired in physical devices

I'm working on an android application and i need alarm manager to fire events at certain times , the code works fine and the notification fires in time but only in one scenario is not working when the screen is off , the device is not waking up and wait for notification to fire up , actually this works in emulators ( i guess because there is no such power saving mode like in some physical devices ) , I've looked up most topics and could not find any solution , any help would be appreciated Thank you .
Firing Alarm Manager
fun fireAlarmManager(context: Context , time : MutableList<Long>){
val intent = Intent(context, AlarmReceiver::class.java)
for (i in 0 until time.size){
if(time[i] > deviceTimeInMillis()){
list.add(time[i])
val pendingIntent = PendingIntent.getBroadcast(context,time[i].toInt(),intent,PendingIntent.FLAG_IMMUTABLE)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,time[i],pendingIntent)
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP,time[i],pendingIntent)
}
}
}
setDataFromSharedPreferences(list)
}
Broadcast receiver
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context : Context?, intent : Intent?) {
wakeUp(context)
val serviceIntent = Intent(context,OnClearFromRecentServices::class.java)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
context!!.startForegroundService(serviceIntent)
} else {
context!!.startService(serviceIntent)
}
}
private fun wakeUp(context: Context?) {
val pm = context!!.getSystemService(Context.POWER_SERVICE) as PowerManager
val wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK or PowerManager.FULL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP, "app::tag")
wakeLock.acquire(60000)
val keyguardManager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
val keyguardLock = keyguardManager.newKeyguardLock("TAG")
keyguardLock.disableKeyguard()
}
}
Alarm Service
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
fireNotification(this)
return START_STICKY
}
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.kotlin.quranapp">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name=".koin.BaseApplication"
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.QuranApp"
android:usesCleartextTraffic="true"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="false"
android:launchMode="singleInstance"
android:screenOrientation="portrait" />
<activity
android:name=".views.SplashActivity"
android:exported="true"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".alarm.AlarmReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<receiver
android:name=".alarm.PlayerReceiver"
android:exported="false" />
<service android:name=".alarm.services.OnClearFromRecentServices" />
</application>
</manifest>

Firebase notification not launching (or launching with delay) app

I'm sending a push notification from Firebase console to my Android App. But sometimes, after receiving the notification and waiting for a couple of hours, and clicking the notification thereafter, it is not opening the app.
PS: In Samsung devices app is opening after a delay of 30+ seconds but in other devices like Mi or Oneplus, it is not opening at all.
Bug video:
In Samsung device
In Mi device
App manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.baja.app">
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:requestLegacyExternalStorage="true"
android:name=".BajaApplication"
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="false"
android:theme="#style/AppTheme.Default"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name=".ui.home.HomeActivity"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter
android:label="#string/app_name"
android:autoVerify="true"
tools:targetApi="m">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accepts URIs that begin with "example://gizmosā€ -->
<data
android:host="#string/share_host"
android:scheme="https" />
</intent-filter>
</activity>
<activity
android:name=".ui.welcome.WelcomeActivity"
android:screenOrientation="portrait" />
<activity
android:name=".ui.home.alarms.ringer.AlarmRingingActivity"
android:screenOrientation="portrait"
android:launchMode="singleInstance" />
<service
android:name=".media.MediaService"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.media.browse.MediaBrowserService" />
</intent-filter>
</service>
<service
android:name=".messaging.BajaFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service
android:name=".ui.welcome.AddressIntentService"
android:exported="false" />
<service
android:name=".media.download.InternalMediaDownloadService"
android:exported="false" />
<service
android:name=".media.download.ExternalMediaDownloadService"
android:exported="false" />
<service android:name=".ui.home.alarms.ringer.AlarmMediaService" />
<receiver android:name=".media.download.DownloadCancelReceiver" />
<receiver
android:name=".ui.home.alarms.AlarmsBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".ui.home.alarms.RescheduleAlarmsService"
android:exported="false" />
<!--
MediaSession, prior to API 21, uses a broadcast receiver to communicate with a
media session. It does not have to be this broadcast receiver, but it must
handle the action "android.intent.action.MEDIA_BUTTON".
Additionally, this is used to resume the service from an inactive state upon
receiving a media button event (such as "play").
-->
<receiver android:name="androidx.media.session.MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver> <!-- Disable crash and analytics reporting for debug builds -->
<meta-data
android:name="firebase_crashlytics_collection_enabled"
android:value="${enableCrashReporting}" />
<meta-data
android:name="firebase_analytics_collection_deactivated"
android:value="${disableAnalyticsReporting}" /> <!-- Set custom default icon and color for request notification -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_favicon" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/black" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="#string/app_fileprovider_authority"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
onMessageReceived method
override fun onMessageReceived(remoteMessage: RemoteMessage) {
val notification: RemoteMessage.Notification = remoteMessage.notification ?: return
val channelId: String = notification.channelId ?: getString(R.string.default_notification_channel)
val (channelCode: Int, #StringRes channelNameRes: Int, #StringRes channelDescRes: Int) =
getNotificationChannelRelatedParams(channelId)
buildAndShowNotification(
notification.title!!,
notification.body!!,
channelId,
notification.imageUrl,
remoteMessage.data,
channelCode,
channelNameRes,
channelDescRes
)
}
Notification builder method
private fun buildAndShowNotification(
title: String,
message: String,
channelId: String,
imageUri: Uri?,
extras: Map<String, String>,
requestCode: Int,
#StringRes channelName: Int,
#StringRes channelDescRes: Int
) {
val defaultSoundUri: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val intent: Intent = Intent(this, HomeActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
extras.keys.forEach { key ->
putExtra(key, extras[key])
}
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val builder: NotificationCompat.Builder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_favicon)
.setColor(Color.BLACK)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setStyle(NotificationCompat.BigTextStyle().bigText(message))
applyImageUrl(builder, imageUri)
val manager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId,
getString(channelName),
NotificationManager.IMPORTANCE_DEFAULT
).apply { description = getString(channelDescRes) }
manager.createNotificationChannel(channel)
}
manager.notify(requestCode, builder.build())
}
Checking notification intent in HomeActivity, if notification handled by system tray
onCreate(..){
//statements
// Check if opened with notification
val intentData: Triple<String, String?, Boolean> = if (savedInstanceState == null) {
playFromIntent(intent, appLaunch = true)
} else {
Triple("", null, false)
}
//statements
}

BOOT COMPLETE BroadcastReceiver automatically being registered

I am trying to start my service when the user wants the service to start on boot. So I have a checkbox preference on my settings fragment to control it. When the box is checked and the user starts the service, the StartOnBootBroadcast BroadcastReceiver will be registered and it will start the service after boot is completed. By default the BroadcastReceiver will not be registered unless the user wants it. But the problem is If I install the app and restarts my device, the broadcast receiver starts the service (BUT I NEVER REGISTERED IT). I've checked the condition with debugger and the conditions never met for starting the receiver.
Broadcast receiver:
class StartOnBootBroadcast : BroadcastReceiver() {
companion object {
private var instance: StartOnBootBroadcast? = null
fun getinstance(): StartOnBootBroadcast {
if (instance == null) {
instance = StartOnBootBroadcast()
}
return instance as StartOnBootBroadcast
}
}
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("BOOTCAST", "onReceive: FIRED")
val serviceIntent = Intent(context, MyService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context!!.startForegroundService(serviceIntent)
} else {
context!!.startService(serviceIntent)
}
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sourav.bettere">
<application
android:name=".App"
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/AppTheme">
<activity
android:name=".activities.MainActivity"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".service.ChargeLoggerService" />
<receiver android:name=".broadcasts.BatteryBroadcast">
<intent-filter>
<action android:name="android.intent.action.BATTERY_CHANGED" />
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
<receiver android:name=".broadcasts.ChargingBroadcast">
<intent-filter>
<action android:name="android.intent.action.BATTERY_CHANGED" />
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
<receiver android:name=".broadcasts.StartOnBootBroadcast">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
Methods for registering / unregistering the BroadcastReciever:
prefViewmodel.getBootStatus.observe(viewLifecycleOwner, Observer { value ->
onBoot = value
if (Utilities.getInstance(mContext).isMyServiceRunning(ChargeLoggerService::class.java)){
startOnBoot(onBoot)
}
})
////unrelated codes
switch.setOnCheckedChangeListener { buttonView, isChecked ->
if (isChecked) {
startService()
Utilities.getInstance(mContext)
.writeToPref(
Constants.PREF_TYPE_BOOL,
Constants.PREF_LOGGER_ACTIVE,
valueBool = true
)
} else {
stopService()
Utilities.getInstance(mContext)
.writeToPref(
Constants.PREF_TYPE_BOOL,
Constants.PREF_LOGGER_ACTIVE,
valueBool = false
)
}
startOnBoot(onBoot)
}
private fun startOnBoot(value: Boolean){
when(value){
true -> Utilities.getInstance(mContext).loadBroadcastReceiver(startOnBoot, IntentFilter(Intent.ACTION_BOOT_COMPLETED))
false -> {
try {
requireContext().unregisterReceiver(startOnBoot)
}catch (e:Exception){
e.printStackTrace()
}}
}
Log.d(TAG, "startOnBoot: $value")
}

App with BroadcastReceiver crashes when triggered on boot

I'm trying to start a service in my app when the phone on which the app is running, boots. I've added a broadcastreceiver, added an intent-filter in the manifest, created a service and added that to the manifest as well. But whenever I boot my phone, after a while it displays that my app has crashed.
An important thing to note is that the service works if it started from MainActivity.
I've seen more questions about this on Stackoverflow, but none of these solve my problem because most of them were of people who forgot to add the receiver to the manifest or something else.
But I don't know how to read logcat-output as well, from when a phone starts, so I can't determine what's crashing the app.
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"
package="nl.arnovanliere.nuntia">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-feature android:name="android.hardware.location.gps" />
<application
android:allowBackup="true"
android:fullBackupContent="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:resizeableActivity="false"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsPictureInPicture="false"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<receiver
android:name=".receivers.BroadcastReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service
android:name=".services.CheckMessagesService"
android:enabled="true"
android:exported="true"
android:permission="false" />
<activity
android:label="#string/app_name"
android:name=".MainActivity"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyBhlLDqLSihI41pIs-ELuomRWUv6513CeE" />
</application>
</manifest>
BroadcastReceiver.kt
class BroadcastReceiver : BroadcastReceiver() {
#SuppressLint("UnsafeProtectedBroadcastReceiver")
override fun onReceive(context: Context?, intent: Intent?) {
context?.startService(Intent(context, CheckMessagesService::class.java))
Log.d(LOG_TAG, "onReceive BroadcastReceiver called")
}
}
CheckMessagesService
class CheckMessagesService : Service() {
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onCreate() {
Log.d(LOG_TAG, "onCreate of service called")
super.onCreate()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(LOG_TAG, "onStartCommand of service called")
val runnable = Runnable {
checkMessages()
// Only need to check for messages every minute
Thread.sleep(60000)
}
// New thread for checking messages, otherwise the UI-thread would be blocked
val thread = Thread(runnable)
thread.start()
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
Log.d(LOG_TAG, "onDestroy of service called")
super.onDestroy()
}
checkMessages() is just a function that calls an API and deserializes it to check if a notification has to be send.
I hope one of you can help me.
For any future viewers: The problem was that I had to use startForegroundService() instead of startService() because I was running it on Android Oreo.
Thanks #Pawel

BroadcastReceiver in Kotlin does not work

Using this manual http://www.techotopia.com/index.php/Kotlin_Android_Broadcast_Intents_and_Broadcast_Receivers#.EF.BB.BFSummary I have implemented BroadcastReceiver in Kotlin so I expect that after rebooting application will start but it does not.
Please, help. Thank you!
BroadcastReceiver
class BroadcastReceiverOnBootComplete : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action.equals(Intent.ACTION_BOOT_COMPLETED, ignoreCase = true)) {
val message = "Broadcast intent detected " + intent.action
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.simplemobiletools.applauncher"
android:installLocation="internalOnly">
<uses-permission
android:name="android.permission.USE_FINGERPRINT"
tools:node="remove"/>
<permission
android:name="com.simplemobiletools.applauncher.permission.INSTALL_SHORTCUT"
android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
android:protectionLevel="dangerous"
android:label="#string/permlab_install_shortcut"
android:description="#string/permdesc_install_shortcut" />
<permission
android:name="com.simplemobiletools.applauncher.permission.READ_SETTINGS"
android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
android:protectionLevel="normal"
android:label="#string/permlab_read_settings"
android:description="#string/permdesc_read_settings"/>
<permission
android:name="com.simplemobiletools.applauncher.permission.WRITE_SETTINGS"
android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
android:protectionLevel="signatureOrSystem"
android:label="#string/permlab_write_settings"
android:description="#string/permdesc_write_settings"/>
<permission
android:name="com.simplemobiletools.applauncher.permission.RECEIVE_LAUNCH_BROADCASTS"
android:protectionLevel="signature"
/>
<permission
android:name="com.simplemobiletools.applauncher.permission.RECEIVE_FIRST_LOAD_BROADCAST"
android:protectionLevel="signatureOrSystem" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.BIND_APPWIDGET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.android.launcher3.permission.READ_SETTINGS" />
<uses-permission android:name="com.android.launcher3.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.android.launcher3.permission.RECEIVE_LAUNCH_BROADCASTS" />
<uses-permission android:name="com.android.launcher3.permission.RECEIVE_FIRST_LOAD_BROADCAST" />
<application
android:name=".App"
android:hardwareAccelerated="true"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_launcher_name"
android:roundIcon="#mipmap/ic_launcher"
android:theme="#style/AppTheme"
android:supportsRtl="true"
android:restoreAnyVersion="true">
<receiver android:name=".activities.BroadcastReceiverOnBootComplete">
<intent-filter>
<action android:name="com.simplemobiletools.applauncher.sendbroadcast" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
<activity
android:launchMode="singleTask"
android:clearTaskOnLaunch="true"
android:stateNotNeeded="true"
android:windowSoftInputMode="adjustPan"
android:screenOrientation="nosensor"
android:resumeWhilePausing="true"
android:taskAffinity=""
android:enabled="true"
android:name=".activities.SplashActivity"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.MONKEY"/>
</intent-filter>
</activity>
<activity android:name=".activities.MainActivity"/>
<activity
android:name=".activities.SettingsActivity"
android:label="#string/settings"
android:parentActivityName=".activities.MainActivity"/>
<activity
android:name="com.simplemobiletools.commons.activities.AboutActivity"
android:label="#string/about"
android:parentActivityName=".activities.MainActivity"/>
<activity
android:name="com.simplemobiletools.commons.activities.LicenseActivity"
android:label="#string/third_party_licences"
android:parentActivityName="com.simplemobiletools.commons.activities.AboutActivity"/>
<activity
android:name="com.simplemobiletools.commons.activities.CustomizationActivity"
android:label="#string/customize_colors"
android:parentActivityName=".activities.SettingsActivity"/>
</application>
</manifest>
MainActivity with BroadcastReceiver
class MainActivity : SimpleActivity(), RefreshRecyclerViewListener {
private var launchers = ArrayList<AppLauncher>()
private var mStoredPrimaryColor = 0
private var mStoredTextColor = 0
private var mStoredUseEnglish = false
private var receiver: BroadcastReceiver? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
appLaunched()
setupLaunchers()
checkWhatsNewDialog()
storeStateVariables()
configureReceiver()
fab.setOnClickListener {
AddAppLauncherDialog(this, launchers) {
setupLaunchers()
}
}
}
override fun onDestroy() {
// super.onDestroy()
unregisterReceiver(receiver)
}
override fun onResume() {
super.onResume()
if (mStoredUseEnglish != config.useEnglish) {
restartActivity()
return
}
if (mStoredTextColor != config.textColor) {
getGridAdapter()?.updateTextColor(config.textColor)
}
if (mStoredPrimaryColor != config.primaryColor) {
getGridAdapter()?.updatePrimaryColor(config.primaryColor)
}
updateTextColors(coordinator_layout)
}
override fun onPause() {
super.onPause()
storeStateVariables()
}
private fun configureReceiver() {
val filter = IntentFilter()
filter.addAction("com.simplemobiletools.applauncher.sendbroadcast")
filter.addAction("android.intent.action.ACTION_POWER_DISCONNECTED")
filter.addAction("android.intent.action.BOOT_COMPLETED")
receiver = BroadcastReceiverOnBootComplete()
registerReceiver(receiver, filter)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.settings -> launchSettings()
R.id.about -> launchAbout()
else -> return super.onOptionsItemSelected(item)
}
return true
}
private fun launchSettings() {
startActivity(Intent(applicationContext, SettingsActivity::class.java))
}
private fun launchAbout() {
startAboutActivity(R.string.app_name, LICENSE_KOTLIN or LICENSE_MULTISELECT or LICENSE_STETHO, BuildConfig.VERSION_NAME)
}
private fun getGridAdapter() = launchers_grid.adapter as? LaunchersAdapter
private fun setupLaunchers() {
launchers = dbHelper.getLaunchers()
checkInvalidApps()
val adapter = LaunchersAdapter(this, launchers, this, launchers_grid) {
val launchIntent = packageManager.getLaunchIntentForPackage((it as AppLauncher).packageName)
if (launchIntent != null) {
startActivity(launchIntent)
finish()
} else {
val url = "https://play.google.com/store/apps/details?id=${it.packageName}"
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(intent)
}
}
adapter.setupDragListener(true)
launchers_grid.adapter = adapter
}
private fun checkInvalidApps() {
val invalidIds = ArrayList<String>()
for ((id, name, packageName) in launchers) {
val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
if (launchIntent == null && !packageName.isAPredefinedApp()) {
invalidIds.add(id.toString())
}
}
dbHelper.deleteLaunchers(invalidIds)
launchers = launchers.filter { !invalidIds.contains(it.id.toString()) } as ArrayList<AppLauncher>
}
private fun storeStateVariables() {
config.apply {
mStoredPrimaryColor = primaryColor
mStoredTextColor = textColor
mStoredUseEnglish = useEnglish
}
}
override fun refreshItems() {
setupLaunchers()
}
private fun checkWhatsNewDialog() {
arrayListOf<Release>().apply {
add(Release(7, R.string.release_7))
checkWhatsNew(this, BuildConfig.VERSION_CODE)
}
}
}
As I could discoverd the prob;em was missing settings here
android:enabled="true"
android:stopWithTask="false"
So it should be like
<receiver android:name=".activities.BroadcastReceiverOnBootComplete" android:enabled="true"
android:stopWithTask="false" >
<intent-filter>
<action android:name="com.simplemobiletools.applauncher.sendbroadcast" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>

Categories

Resources