如何创建后台通知

时间:2014-04-29 12:19:27

标签: android android-notifications

即使我关闭了应用程序,我也希望实现允许显示通知(每天或在XX分钟后)的服务。 (实际上,当我按下后退按钮时,我完成了MainActivity ......)

即使我没有启动应用程序,我也需要一个可运行的通知(例如,在重启设备之后,当然,当触发器被解除时)...

我尝试了一些明确的示例和教程,但我找不到我需要的东西。

请帮助!

提前致谢, 穆罕默德

1 个答案:

答案 0 :(得分:1)

您可以使用闹钟管理器执行此操作:

public class AlarmHelper {

private Context context;
private AlarmManager alarmManager;
private static final String TAG = "AlarmHelper";
public final static String ALARM_ALERT_ACTION = "com.android.alarmclock.ALARM_ALERT";

public AlarmHelper(Context context) {
    this.context = context;
    alarmManager = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
}

public void setNotifyAlarm(Long milliSecond) {

    PendingIntent pendingIntent = getNotifyPendingIntent();
    alarmManager.cancel(pendingIntent);
    alarmManager.set(AlarmManager.RTC_WAKEUP, milliSecond, pendingIntent);
    // alarmManager.set(AlarmManager.RTC_WAKEUP, milliSecond, sender);
}

public void cancelNotifyAlarm() {
    PendingIntent pendingIntent = getNotifyPendingIntent();
    alarmManager.cancel(pendingIntent);
}

private PendingIntent getNotifyPendingIntent() {
    Intent intent = new Intent(context, AlarmExpireService.class);
    return PendingIntent.getService(context, 0, intent, 0);
}

public void setExpireAlarm(int minute) {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, minute - 1);

    PendingIntent pendingIntent = getExpirePendingIntent();
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            pendingIntent);
}

public void cancelExpireAlarm() {
    PendingIntent pendingIntent = getExpirePendingIntent();
    alarmManager.cancel(pendingIntent);
}

private PendingIntent getExpirePendingIntent() {
    return PendingIntent.getService(context, 0, new Intent(context,
            AlarmExpireService.class), 0);
}

}

现在在AlarmExpireService.java中:

public class AlarmExpireService extends Service {

// private static final String TAG = "AlarmExpireService";
private static final String TAG = "AlarmExpireService";


@Override
public void onCreate() {
    super.onCreate();
    //your logic for start activity or generate notification.
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    AppLog.Log(TAG, "On start command");
    return START_STICKY;
}

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

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

}

}

现在在清单文件中注册服务:

 <service android:name="your_package.AlarmExpireService" />

只需从AlarmHelper的setNotifyAlarm方法调用一个方法,你的工作就完成了以毫秒为单位的时间(它会在那段时间后开始,并会弹出通知)。

有关更多信息,请参考以下链接: 1. AlarmManager 2. Service 3。Pending Intent