简体   繁体   中英

Repeating actions using Alarm in Android background service

I wrote this code in MainService.java that is called in foreground by using startForeground method. I want to make a toast message in every 10 seconds but it doesn't work. How can I fix it??


public void Alarm(){
        Intent intent = new Intent("AlarmService");
        PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
        long firstTime = SystemClock.elapsedRealtime() + 10 * 1000;
        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, sender) ;
            } else {
                am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, sender);
            }
        } else {
            am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, sender);
        }
    }

    BroadcastReceiver alarmReceiver;
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        alarmReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub\
                count++;
                Toast.makeText(getApplicationContext(),count+"times",Toast.LENGTH_LONG);
                Alarm();
            }
        };
        registerReceiver(alarmReceiver, new IntentFilter("AlarmService"));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM