How to repeat an action every day in an Android app?

冷暖自知 提交于 2019-12-07 21:37:34

问题


I want to repeat an action every day; it must continue working even if the app is not running or the device has been restarted (rebooted). In my code I'm trying to show a TOAST message every 1 minute (as a test); it's working fine in the emulator but on a real device it doesn't work( i tried to do some changes to fixed as i see in some answers but still the same thing)

MyReceiver

class MyReceiver : BroadcastReceiver() {
    private val channelId = "com.medanis.hikamwahimam"

    override fun onReceive(context: Context, intent: Intent) {
        Log.i("TAG","/////////////////// SHOW NOTIFICATION NOW //////////////////////")
        val builder = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.ic_stat_name)
            .setLargeIcon(BitmapFactory.decodeResource(context.resources,R.mipmap.ic_launcher_round))
            .setContentTitle("My notification")
            .setContentText("Much longer text that cannot fit one line...")
            .setStyle(
                NotificationCompat.BigTextStyle()
                    .bigText("Much longer text that cannot fit one line...Much longer text that cannot fit one line..."))
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        with(NotificationManagerCompat.from(context)) {
            notify(12345, builder.build()) }
        Toast.makeText(context,"This toast will be shown every X minutes", Toast.LENGTH_LONG).show()
    }
}

MainActivity

class MainActivity : AppCompatActivity() {
    private var mAlarmManager : AlarmManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
//        showNotification()

        val mIntent = Intent(this, MyReceiver::class.java)

        val mPendingIntent = PendingIntent.getBroadcast(this, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT)
        mAlarmManager = this
            .getSystemService(Context.ALARM_SERVICE) as AlarmManager
        mAlarmManager!!.setRepeating(
            AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
            60000, mPendingIntent
        )
    }
}

AndroidManifest.xml

<receiver android:name=".MyReceiver" >
</receiver>

The Issues are :

1/- This code does not work with REAL DEVICE.

2/- This code does not work if the user restart his device.

A sample on GitHub (i had made some changes as my friend had suggested but still the same errors)


回答1:


1/- This code does not work with REAL DEVICE.

I've downloaded your project, run on my device and it works, it shows the Toast when I click start, and every minute is showing.

I recommend you to take a look on this question

2/- This code does not work if the user restart his device.

If you want to restart your BroadcastReceiver once the device is rebooted or shut downed, you may want to add this code :

Add this in your manifest.xml

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

Create another receiver in manifest.xml

<receiver android:name=".BootCompletedIntentReceiver">
   <intent-filter>
     <action android:name="android.intent.action.BOOT_COMPLETED" />
   </intent-filter>
</receiver>

And then create a BroadcastReceiver as you did previously for showing the Toast

class BootCompletedIntentReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        if ("android.intent.action.BOOT_COMPLETED" == intent.action) {
          //Start your old broadcastreceiver
        }
    }
}

For more information you can take a look at this post

Hope it helps.



来源:https://stackoverflow.com/questions/55396123/how-to-repeat-an-action-every-day-in-an-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!