android how to completely withdraw APP delay recall notice, achieve timing push information to the notification bar

Copyright: come, do not argue with bald? Burnished burnished kind Oh, Great God reprint please indicate the source https://blog.csdn.net/yue_233/article/details/89474170

android how to completely withdraw APP delay recall notice, achieve timing push information to the notification bar


Well, project director at YY happy when I came to mention a demand: When the game exit, please note that not quit the background, is the kind of completely out of you to add a function: 8 hours after the pop-up notification, you want to hurry up and play the game, what sleep sleep! ! ! Good robber, there are policy has Sun Ce, under mysterious policy, Okay, this is a little difficult to start playing, then open and doing, to see the face of money ------

Achieve timing push information to the notification bar
Analysis:
1. How to trigger a notification, it is certainly broadcast it (Note: Android p does not support static broadcast, trained, trained, trained).
2. How to ensure the trigger, open service? Not like a lot of people say have a reception, there is a Paul II, see dizziness, Google smile.
3.Delayed treatment, within 8 hours, re-enter the game, to cancel the last trigger a notification.

achieve:

1. Of course, a broadcast receiver is registered

NotificationReceiver :

public class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
    
        if (intent.getAction().equals("com.example.yy.game_notification")) {
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                    new Intent(context, MainActivity.class), 0);
            Notification notify = new Notification.Builder(context)
                    .setSmallIcon(R.drawable.icon)
                    .setTicker("TickerText:" + "睡什么睡 ** 起来嗨!")
                    .setContentTitle("温馨提示:")
                    .setContentText(""睡什么睡 ** 起来嗨!")
                    .setContentIntent(pendingIntent).setNumber(1).build();
            notify.flags |= Notification.FLAG_AUTO_CANCEL;
            NotificationManager manager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(1, notify)
        }
    }
}

2. Call AlarmManager (Baidu own use), set an alarm clock, the timing of transmitting a broadcast

public void setAlarmOnetoNotification(int time, boolean issetalarm) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent();
        intent.setAction("com.example.yy.game_notification");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0x101, intent, 0);
        if (issetalarm) {
            long triggerAtTime = SystemClock.elapsedRealtime() + time; //获取手机开机到现在的时间 加上你要延时的时间
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pendingIntent);//未设提醒,设置提醒
        } else{
			alarmManager.cancel(pendingIntent);//已设提醒,取消之前提醒,重新设置
}

3. Add judgment in place exit (exit) of the game, used to determine retention time stamp (I here superfluous)

if (getExitGameTime() == null) {
    setAlarmOnetoNotification(GAME_NOTIFICATION_TIME, true);//传入你要定时的时长以及是否是已设置
    saveExitGameTime(System.currentTimeMillis());
} else {
    setAlarmOnetoNotification(GAME_NOTIFICATION_TIME, false);
    setAlarmOnetoNotification(GAME_NOTIFICATION_TIME, true);
}

Small ways: retention time stamp:

	public void saveExitGameTime(long exittime) {
        SharedPreferences sharedPreferences = getSharedPreferences("ExitGametime", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("currentExitTime", stampToDate(exittime));
        editor.commit();
    }

    public String getExitGameTime() {
        SharedPreferences sharedPreferences = getSharedPreferences("ExitGametime", Context.MODE_PRIVATE);
        String str = sharedPreferences.getString("currentExitTime", null);
        return str;
    }

    /**
     * 将时间转换为时间戳
     */
    public String dateToStamp(String time) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(time);
        long ts = date.getTime();
        return String.valueOf(ts);
    }

    /**
     * 将时间戳转换为时间
     */
    public String stampToDate(long timeMillis) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(timeMillis);
        return simpleDateFormat.format(date);
    }

Currently self-test OK, quit after two hours after the pop-up tips

There are big God said: changing time zones, alarm clock may AlarmManager set will not work, and then after the shutdown seems to have no effect, ah, talk to the project director to talk about ...

Reference Code: https://blog.csdn.net/myfwjy/article/details/51726072

I lack experience (first blog), there is a problem (have a problem) welcome that, learn from each other ...
for the first time to add:
Android has been updated, some say the timing will increase as the version without accurate
so I looked timing type:
Here Insert Picture Descriptiontoo le, to release the adaptation:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pendingIntent);//未设提醒,设置提醒
            } else {
                alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pendingIntent);//未设提醒,设置提醒
            }

There are many online super fit, you can refer to
say that what I have a problem:
Timing effective (how to on how to think) on a virtual machine, on a real machine, four hours have effect (app in the background, do not quit case), 8 hours has no effect (background process guess is killed), exit the app, there is no effect ---- Turn the tables
find a lot of information, also tried, to no avail, and later found a big God said:
About Android the AlarmManager after use without waking question:
https://blog.csdn.net/qq_38679144/article/details/78867210
let's try again ...
cause of the problem occurred: the system banned since the launch of the application
I am using a millet test machine, there is a set of management from the start, after opening the authorization app, 8 hours timer pop-up notification is valid, the code function OK, this also explains another problem, why the phone comes with alarm clock timer can be effective, the system comes with permissions
on the market for many applications why it can also push message at the end of the application? Access is said to be a push sdk ...

Guess you like

Origin blog.csdn.net/yue_233/article/details/89474170