我想每天重复一个动作;即使应用程序未运行或设备已重新启动(重新启动),它也必须继续工作。在我的代码中,我试图每 1 分钟显示一条 TOAST 消息(作为测试);它在模拟器中工作正常,但在真实设备上它不起作用(我尝试对修复进行一些更改,正如我在一些答案中看到的但仍然是一样的)
我的接收器
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()
}
}
主要活动
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。
2/- 如果用户重新启动他的设备,此代码将不起作用。
GitHub 上的示例(我按照朋友的建议做了一些更改,但仍然出现相同的错误)