android - 如果用户 3 天不活动,如何发送通知

标签 android

我正在开发一个 Android 应用程序,如果他/她超过 3 天不活动,我想向用户发送“我们想念你”通知。 这意味着如果用户 3 天没有打开我们的应用程序,我想向他们发送“我们想念你”的通知 就像猎鹿人和神庙逃亡一样 谢谢:)

最佳答案

您想设置一个每天启动一次短期运行服务的警报。该服务所做的只是检查上次使用时间的共享偏好之类的东西。如果该时间超过 3 天,则服务会发送通知。无论哪种方式,服务都会退出。

或者,您的应用可以在每次运行时提交一个警报,该警报被定义为在 3 天内触发并被定义为替换具有相同 ID 的任何预先存在的警报。该警报将被定义为打开一个发送通知的短期运行服务。

下面是一些演示第二种方法的示例代码。如所写,它仅在启动时更新运行时间。如果您的应用程序长时间运行,您需要定期调用 recordRunTime()。如果将 Notification.Builder 对象替换为 NotificationCompat.Builder,则可以将已弃用的方法 getNotification() 替换为 build()。您可以使用注释掉的 delay 行来测试更短的延迟时间。

主 Activity .java:

package com.example.comeback;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {

private final static String TAG = "MainActivity";
public final static String PREFS = "PrefsFile";

private SharedPreferences settings = null;
private SharedPreferences.Editor editor = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    // Save time of run:
    settings = getSharedPreferences(PREFS, MODE_PRIVATE);
    editor = settings.edit();

    // First time running app?
    if (!settings.contains("lastRun"))
        enableNotification(null);
    else
        recordRunTime();

    Log.v(TAG, "Starting CheckRecentRun service...");
    startService(new Intent(this,  CheckRecentRun.class));
}

public void recordRunTime() {
    editor.putLong("lastRun", System.currentTimeMillis());
    editor.commit();        
}

public void enableNotification(View v) {
    editor.putLong("lastRun", System.currentTimeMillis());
    editor.putBoolean("enabled", true);                
    editor.commit();        
    Log.v(TAG, "Notifications enabled");
}

public void disableNotification(View v) {
    editor.putBoolean("enabled", false);                
    editor.commit();        
    Log.v(TAG, "Notifications disabled");
}

CheckRecentRun.java:

package com.example.comeback;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

public class CheckRecentRun extends Service {

    private final static String TAG = "CheckRecentPlay";
    private static Long MILLISECS_PER_DAY = 86400000L;
    private static Long MILLISECS_PER_MIN = 60000L;

//  private static long delay = MILLISECS_PER_MIN * 3;   // 3 minutes (for testing)
    private static long delay = MILLISECS_PER_DAY * 3;   // 3 days

    @Override
    public void onCreate() {
        super.onCreate();

        Log.v(TAG, "Service started");                
        SharedPreferences settings = getSharedPreferences(MainActivity.PREFS, MODE_PRIVATE);

        // Are notifications enabled?
        if (settings.getBoolean("enabled", true)) {
            // Is it time for a notification?
            if (settings.getLong("lastRun", Long.MAX_VALUE) < System.currentTimeMillis() - delay)
                sendNotification();

        } else {        
            Log.i(TAG, "Notifications are disabled");
        }

        // Set an alarm for the next time this service should run:
        setAlarm();

        Log.v(TAG, "Service stopped");        
        stopSelf();
    }

    public void setAlarm() {

        Intent serviceIntent = new Intent(this, CheckRecentRun.class);
        PendingIntent pi = PendingIntent.getService(this, 131313, serviceIntent,
                                                    PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delay, pi);
        Log.v(TAG, "Alarm set");        
    }

    public void sendNotification() {

        Intent mainIntent = new Intent(this, MainActivity.class);
        @SuppressWarnings("deprecation")
        Notification noti = new Notification.Builder(this)
            .setAutoCancel(true)
            .setContentIntent(PendingIntent.getActivity(this, 131314, mainIntent,
                              PendingIntent.FLAG_UPDATE_CURRENT))
            .setContentTitle("We Miss You!")
            .setContentText("Please play our game again soon.")
            .setDefaults(Notification.DEFAULT_ALL)
            .setSmallIcon(R.drawable.ic_launcher)
            .setTicker("We Miss You! Please come back and play our game again soon.")
            .setWhen(System.currentTimeMillis())
            .getNotification();

        NotificationManager notificationManager
            = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(131315, noti);

        Log.v(TAG, "Notification sent");        
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

主要 Activity 布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="enableNotification"
        android:text="@string/enable" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="disableNotification"
        android:text="@string/disable" />

</LinearLayout>

字符串.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Come Back</string>
    <string name="enable">Enable Notifications</string>
    <string name="disable">Disable Notifications</string>

</resources>

AndroidManifest.com:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.comeback"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.comeback.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name="com.example.comeback.CheckRecentRun" >
        </service>
        </application>

</manifest>

关于android - 如果用户 3 天不活动,如何发送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22709751/

相关文章:

android - 如何通过 SharedPreferences 保存解析的推送通知

java - 将数据发送到 viewpager 的特定 fragment

android - SimpleDateFormat 解析器

java - 加密和解密xml

android - 使用 MediaRecorder 在 android 中录制语音通话

c# - Xamarin.Android Material 设计图标

android - 概览键的键事件代码是什么?

java - 在Android(使用Java)中,如何设置铃声音量(到指定的数字)?

android - 在库中添加 Gradle 构建文件夹

android - 无法在 androidx.appcompat.widget.TintContextWrapper 中为 MaterialButton 中的 onClick 处理程序找到自定义方法