如果用户不活动3天,如何发送通知 [英] How to send notification if user inactive for 3 days

查看:155
本文介绍了如果用户不活动3天,如何发送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Android应用程序,如果用户闲置超过3天,我想向其发送我们想念您"通知.这意味着如果用户在3天内没有打开我们的应用,我想向他们发送我们想念您"的通知就像《猎鹿人》和《神庙逃亡》一样谢谢:)

I am developing an android app and I want to send "We Miss You" notification to user if he/she is inactive for more than 3 days. This means if the user does not open our app for 3 days I want to send them a notification of "We Miss you" Like Deer Hunter and Temple Run sends Thank you :)

推荐答案

您要设置一个每天启动一次短期运行服务的警报.该服务所要做的只是检查上次使用的共享首选项之类的内容.如果该时间已超过3天,则该服务会发送通知.无论哪种方式,服务都将退出.

You want to set an alarm that starts a short-running service once per day. All that service does is to check something like a shared preference for the last-used-time. If that time is more than 3 days old, then the service sends a notification. Either way, the service then exits.

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

Alternatively, your app could submit an alarm, each time it runs, that is defined to fire in 3 days and defined to replace any pre-existing alarm with the same ID. That alarm would be defined to open a short-running service that sends a notification.

这里有一些示例代码演示了第二种方法.如所写,它仅在启动时更新运行时间.如果您的应用程序长时间运行,则需要定期调用 recordRunTime().如果将Notification.Builder对象替换为NotificationCompat.Builder,则不推荐使用的方法 getNotification()可以替换为 build().您可以将带注释的行用于 delay ,以较短的延迟时间进行测试.

Here's some sample code that demonstrates the second approach. As written, it only updates the run time upon start-up. If your app is long-running, you'll want to call recordRunTime() periodically. The deprecated method getNotification() could be replaced with build() if the Notification.Builder object was replaced with a NotificationCompat.Builder. You can use the commented out line for delay to test with a shorter delay time.

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");
}

}

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;
    }
}

main_activity_layout:

<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>

strings.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>

这篇关于如果用户不活动3天,如何发送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆