如何每天在Android应用程序中重复操作? [英] How to repeat an action every day in an Android app?
问题描述
我想每天重复一次动作;即使应用未运行或设备已重新启动(重新启动),它也必须继续工作. 在我的代码中,我试图每1分钟显示一条TOAST消息(作为测试);在模拟器中可以正常工作,但在真实设备上却无法工作(我尝试对某些问题进行修改,如我在某些答案中看到的,但仍然是同一件事)
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)
我的接收器
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>
问题是:
1/-此代码不适用于REAL DEVICE.
1/- This code does not work with REAL DEVICE.
2/-如果用户重新启动设备,此代码将不起作用.
2/- This code does not work if the user restart his device.
GitHub 上的示例(我已经制作了像我的朋友建议的那样进行了一些更改,但仍然是相同的错误)
A sample on GitHub (i had made some changes as my friend had suggested but still the same errors)
推荐答案
1/-此代码不适用于REAL DEVICE.
1/- This code does not work with REAL DEVICE.
我已经下载了您的项目,并在我的设备上运行,并且可以运行,当我单击开始"时,它会显示Toast
,并且每分钟都会显示.
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.