0

I was learning about alarms. I created an app where clicking on button would send you a notification after 5 seconds. The app works fine when it is on screen. But it does not work when my app goes to background after pressing the button. The notification which was supposed to come, comes only after I open my app

I have tried changing the setting of my Samsung phone by changing the option "Putting unused app to sleep " to false in settings. But still it did not work.

is there something wrong with my code? or do I need to use some sort of permissions?

Code: activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Alarm!"
        android:id="@+id/btn"
       />

</LinearLayout>

MainActivity.kt:

package com.example.alarms1

import android.app.*
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PowerManager
import android.os.SystemClock
import android.widget.Toast
import androidx.core.app.NotificationCompat
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            var packageName = this .getPackageName();
            var pm = getSystemService(POWER_SERVICE) as PowerManager;
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                var intent =Intent();
                intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setData(Uri.parse("package:" + packageName));
                startActivity(intent);
            }
        }
        Toast.makeText(this,"Hello",Toast.LENGTH_SHORT).show();
        btn.setOnClickListener {

            var int=Intent(this,MainActivity2::class.java)
            var pi=PendingIntent.getActivity(this,123,int,PendingIntent.FLAG_ONE_SHOT);
            var myAlarmm=getSystemService(ALARM_SERVICE) as AlarmManager;
            myAlarmm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime()+5000,pi);
        }
    }
}

activity_main2.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity2.kt:

package com.example.alarms1

import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.app.NotificationCompat

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

        var nm=getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.O)
            nm.createNotificationChannel(
                NotificationChannel("Channel1","Name1",
                    NotificationManager.IMPORTANCE_DEFAULT)
            )

        var myNotification= NotificationCompat.Builder(this,"Channel1")
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentTitle("Hello World")
            .setContentText("Hello namaste stasriaka").build()
        nm.notify(123,myNotification);

        finish();
    }
}

Also I have made my activity_main2 to be transparent which works fine

James Z
  • 12,209
  • 10
  • 24
  • 44
Gagan Walia
  • 131
  • 5
  • try this answer. https://stackoverflow.com/questions/34378707/alarm-manager-does-not-work-in-background-on-android-6-0 – Rafa Jul 07 '21 at 20:07

2 Answers2

1

Samsung is aggressive about killing things that run in the background. A full list of things you might want to look at (depending on your model and OS version) is available at dontkillmyapp.com/samsung, but a short list is:

  1. Disable "Put unused apps to sleep"
  2. Disable "Auto-disable unused apps"
  3. Remove your app from the list of "Sleeping" apps
  4. Disable background restrictions for your app
user3486184
  • 2,147
  • 3
  • 26
  • 28
0

You need to try use JobServices(https://developer.android.com/reference/android/app/job/JobService) or/and with Worker(https://developer.android.com/topic/libraries/architecture/workmanager/advanced/worker) depends on your requirements and Android SDK. I you still want to use AlarmManager take a look ob this thread: Alarm Manager does not work in background on Android 6.0

LifeStyle
  • 411
  • 2
  • 10