2014-09-29 72 views
1

我试图在Android中实施通知服务,每天触发警报管理器。我读过,警报管理器setRepeating()的方法已从API 18更改为API 19.因此,您现在应该使用setExact()。 我目前在API 18上实现。所以这不应该影响我。我使用setRepeating(),并且第一次发布通知是在正确的时间。但后来它变得疯狂:D通知不断被解雇。有时三次接一次,然后两天没事。Android日常通知设置重复垃圾邮件

我的代码: 第一次我的应用程序正在启动以下行会被执行:

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

我NotifyService类看起来是这样的:

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 w ith API 19,每次我的通知被触发时调用setExact,但没有成功。

没有人有什么想法吗?

回答

2

如果有人正在寻找答案我的问题: 这是我做了什么,什么工作。

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

mNM.notify(1, mNotify); 

添加此调用:

stopSelf(); 

这为我工作。

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

所以你的接收机类:

public class BootCompleteReceiver extends BroadcastReceiver { 

    private PendingIntent pendingIntent; 

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

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

    } 
} 

而在你的清单中添加:

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