android-本地推送

Android本地推送,即使游戏进程被杀,一样可以本地推送。
Q2现在就是用这种本地推送。


1. 加入以下java类

这里写图片描述

2. 主工程Android配置文件AndroidManifest.xml加入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- notify Start -->
<activity
android:configChanges="orientation"
android:label="@string/app_name"
android:launchMode="singleTask"
android:screenOrientation="sensorLandscape"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:name="com.qtz.game.utils.ClickActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<receiver
android:name="com.qtz.game.utils.TriggerReceiver"
android:exported="false">
</receiver>
<receiver
android:name="com.qtz.game.utils.ClearReceiver"
android:exported="false">
</receiver>
<!-- notify End -->

3. 使用接口

  1. 增加推送

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    private static int counter = 0; //全局唯一计数
    // pContext 游戏主context

    //本地alarm推送
    int id = counter++;
    String isStr = String.valueOf(id);
    try {
    JSONObject dict = new JSONObject();
    dict.put("id", isStr);
    dict.put("text", msg);
    dict.put("at", System.currentTimeMillis() / 1000 + delay);
    dict.put("smallIcon", "icon");
    dict.put("icon", "icon");
    if (repeats == 1) {
    dict.put("every", "day");
    } else if (repeats == 2) {
    dict.put("every", "hour");
    } else if (repeats == 3) {
    dict.put("every", "minute");
    } else if (repeats == 4) {
    dict.put("every", "second");
    }
    Manager.getInstance(pContext).schedule(dict);

    //丢进本地文件保存,以便重启游戏是清除
    SharedPreferences prefs = pContext.getSharedPreferences(NotificationTmp.PUSH_IDS_FILE, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(isStr, isStr);
    editor.commit();

    } catch (JSONException e) {
    e.printStackTrace();
    }
  2. 清除所有推送

    1
    2
    3
    counter = 0;
    Manager.getInstance(pContext).cancelAll();
    Manager.cleanAllInfo(pContext);

4. 说明

  1. 本地保存的两个数据文件,xml格式
    这里写图片描述

    • LocalNotificationIds : 保存所有增加的推送id,用于清除推送时使用
    • LocalNotificationSet : 保存现有需要显示的通知及其内容,用于显示通知栏显示所以已有的推送信息。
  2. 清除所有通知原理(被坑了有点久)。本地使用闹钟进行通知,清除需要的数据需要严格一致(Google了好久)

    • 增加
      这里写图片描述
    • 清除
      这里写图片描述