Android每日通知设置重复垃圾邮件

时间:2014-09-29 19:52:02

标签: service notifications alarmmanager spam

我试图在Android中实施通知服务,每天触发购买警报管理器。我读过,alarmmanager setRepeating()的方法已从API 18更改为API 19.所以您现在应该使用setExact()。 我目前正在API 18上实施。所以这不应该影响我。我使用setRepeating()并且第一次触发通知是在正确的时间。但后来它变得疯狂:D通知随机被激活。有时3次接连,然后2天没什么。

我的代码: 第一次启动我的应用程序时,将执行以下行:

private void startAlarm(){
   Calendar calendar = Calendar.getInstance();

   calendar.set(Calendar.SECOND, 0);
   calendar.set(Calendar.MINUTE, 30);
   calendar.set(Calendar.HOUR, 7);
   calendar.set(Calendar.AM_PM, Calendar.PM);
   calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH));

   Intent myIntent = new Intent(this , NotifyService.class);
   AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
   pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
   alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24, pendingIntent);
}

My NotifyService Class如下所示:

public class NotifyService extends Service {

 private PendingIntent pendingIntent;

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

 @Override
 public void onCreate(){
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);

    Notification mNotify = new NotificationCompat.Builder(this)
            .setAutoCancel(true)
            .setContentTitle(text)
            .setContentText(text)
            .setSmallIcon(R.drawable.pic)
            .setContentIntent(pIntent)
            .setSound(sound)
            .build();

    mNM.notify(1, mNotify);
 }
}

相关进口是:

import android.support.v4.app.NotificationCompat;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;

我还尝试将setExact与API 19一起使用,并在每次我的通知被触发时调用setExact,但没有成功。

没有人有任何想法?

1 个答案:

答案 0 :(得分:2)

如果有人正在寻找我的问题的答案: 这就是我所做的和有效的方法。

您需要停止您创建的服务。所以在我下面的NotifyService类中

mNM.notify(1, mNotify);

添加此电话:

stopSelf();

这对我有用。

编辑: 如果您希望即使设备已关闭也会显示通知,您需要添加一个Boot_Completed接收器。

所以你的接收器类:

public class BootCompleteReceiver extends BroadcastReceiver {

   private PendingIntent pendingIntent;

   @Override
   public void onReceive(Context context, Intent intent) {

      startAlarm(); // See Method above (in Question)

   }
}

在你的Manifest中添加:

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

 <receiver
        android:name="package.BootCompleteReceiver"
        android:process=":remote" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
 </receiver>