启动时启动警报不起作用

时间:2015-05-26 09:18:56

标签: android broadcastreceiver android-notifications

我创建了一个BroadcastReceiver,在那里我启动了3个警报和3个通知,但我尝试了我的代码并且它没有工作,警报没有触发。 我还尝试将通知代码包含在if条件中,但是当通知应该启动应用程序崩溃时。 这是我的BroadcastReceiver代码:

 @Override
    public void onReceive(Context context, Intent intent)
    {
         if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
             setAlarm(context);
         }
        String keyid = intent.getStringExtra("number");
        String notif=PreferenceManager.getDefaultSharedPreferences(context).getString("notif", "abilitato");
        if(notif.equals("abilitato")){          
        if(keyid.equals("0")){
        Intent notificationIntent = new Intent(context, MainActivity.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(context,
                        0, notificationIntent,
                        PendingIntent.FLAG_CANCEL_CURRENT);
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
         NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(context);
         mBuilder.setContentIntent(contentIntent)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle("E' ora di colazione!")
                    .setContentText("Cosa c'è per colazione?")
                    .setSound(alarmSound)
                    .setLights(Color.BLUE, 1000, 500)
                    .setVibrate(new long[] { 1000, 1000})
                    .setAutoCancel(true);


                NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(1, mBuilder.build());
        }
        if(keyid.equals("1")){

            Intent notificationIntent = new Intent(context, MainActivity.class);
            notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent contentIntent = PendingIntent.getActivity(context,
                            1, notificationIntent,
                            PendingIntent.FLAG_CANCEL_CURRENT);
            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
             NotificationCompat.Builder mBuilder2 =
                        new NotificationCompat.Builder(context);
             mBuilder2.setContentIntent(contentIntent)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle("E' ora pranzo!")
                        .setContentText("Cosa c'è per pranzo?")
                        .setSound(alarmSound)
                        .setLights(Color.BLUE, 1000, 500)
                        .setVibrate(new long[] { 1000, 1000})
                        .setAutoCancel(true);

                    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(1, mBuilder2.build());
        }
        if(keyid.equals("2")){
            Intent notificationIntent = new Intent(context, MainActivity.class);
            notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent contentIntent = PendingIntent.getActivity(context,
                            2, notificationIntent,
                            PendingIntent.FLAG_CANCEL_CURRENT);
            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
             NotificationCompat.Builder mBuilder3 =
                        new NotificationCompat.Builder(context);
                       mBuilder3.setContentIntent(contentIntent)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle("E' ora cena!")
                        .setContentText("Cosa c'è per cena?")
                        .setSound(alarmSound)
                        .setLights(Color.BLUE, 1000, 500)
                        .setVibrate(new long[] { 1000, 1000})
                        .setAutoCancel(true);


                    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(1, mBuilder3.build());
            }
           }   

    }
    public void setAlarm(Context context){
        String breakfast1=PreferenceManager.getDefaultSharedPreferences(context).getString("breakfast", "abilitato"); 
        String lunch1=PreferenceManager.getDefaultSharedPreferences(context).getString("lunch", "abilitato"); 
        String dinner1=PreferenceManager.getDefaultSharedPreferences(context).getString("dinner", "abilitato"); 
        Database d;
        AlarmManager alarmManager;
        PendingIntent pendingIntent;
         d=new Database(context);
         String dataString=d.checkDataString();
          String n;

         //COLAZIONE
         int duepunti = breakfast1.indexOf(":");
         String hourColazione = breakfast1.substring(0,duepunti);
         int intHourColazione=Integer.parseInt(hourColazione);
         String minuteColazione = breakfast1.substring(duepunti + 1);
         int intMinuteColazione=Integer.parseInt(minuteColazione);

         int start = dataString.indexOf("/");
         String dayString = dataString.substring(0,start);
         String monthString = dataString.substring(start + 1,start+3);
         String yearString = dataString.substring(start+4);
         int day = Integer.parseInt(dayString);
         int month = Integer.parseInt(monthString);
         int year = Integer.parseInt(yearString); 
         Calendar calNow = Calendar.getInstance();
          Calendar c = (Calendar) calNow.clone();
          c.setTimeInMillis(System.currentTimeMillis());
          c.set(Calendar.YEAR, year);
          c.set(Calendar.MONTH, month-1);
          c.set(Calendar.DAY_OF_MONTH, day);
         c.set(Calendar.HOUR_OF_DAY, intHourColazione);
         c.set(Calendar.MINUTE, intMinuteColazione);
         c.set(Calendar.SECOND, 0);    
         c.set(Calendar.MILLISECOND, 0);
         if(c.after(System.currentTimeMillis())){
             c.add(Calendar.DAY_OF_MONTH, 1);
         }
         Intent myIntent = new Intent(context, MyReceiver.class);

         n="0";
         myIntent.putExtra("number", n);
         if(PendingIntent.getBroadcast(context, 0, 
                myIntent, 
                PendingIntent.FLAG_NO_CREATE) == null){

         pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent,0);
         alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
         alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

      }
       //PRANZO  
         int duepunti2 = lunch1.indexOf(":");
         String hourPranzo = lunch1.substring(0,duepunti2);
         int intHourPranzo=Integer.parseInt(hourPranzo);
         String minutePranzo = lunch1.substring(duepunti2 + 1);
         int intMinutePranzo=Integer.parseInt(minutePranzo); 

         Calendar calNow2 = Calendar.getInstance();
          Calendar c2 = (Calendar) calNow2.clone();
          c2.setTimeInMillis(System.currentTimeMillis());
          c2.set(Calendar.YEAR, year);
          c2.set(Calendar.MONTH, month-1);
          c2.set(Calendar.DAY_OF_MONTH, day);
         c2.set(Calendar.HOUR_OF_DAY, intHourPranzo);
         c2.set(Calendar.MINUTE, intMinutePranzo);
         c2.set(Calendar.SECOND, 0);    
         c2.set(Calendar.MILLISECOND, 0);
         if(c2.after(System.currentTimeMillis())){
             c2.add(Calendar.DAY_OF_MONTH, 1);
        }
         Intent myIntent2 = new Intent(context, MyReceiver.class);
         n="1";
         myIntent2.putExtra("number", n);
         if(PendingIntent.getBroadcast(context, 1, 
                myIntent2, 
                PendingIntent.FLAG_NO_CREATE) == null){

         pendingIntent = PendingIntent.getBroadcast(context, 1, myIntent2 ,0);
         alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
         alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c2.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

      }
         //CENA
         int duepunti3 = dinner1.indexOf(":");
         String hourCena = dinner1.substring(0,duepunti3);
         int intHourCena=Integer.parseInt(hourCena);
         String minuteCena = dinner1.substring(duepunti3 + 1);
         int intMinuteCena=Integer.parseInt(minuteCena);
         Calendar calNow3 = Calendar.getInstance();
          Calendar c3 = (Calendar) calNow3.clone();
          c3.setTimeInMillis(System.currentTimeMillis());
          c3.set(Calendar.YEAR, year);
          c3.set(Calendar.MONTH, month-1);
          c3.set(Calendar.DAY_OF_MONTH, day);
          c3.set(Calendar.HOUR_OF_DAY, intHourCena);
          c3.set(Calendar.MINUTE, intMinuteCena);
          c3.set(Calendar.SECOND, 0);    
          c3.set(Calendar.MILLISECOND, 0);
          if(c.after(System.currentTimeMillis())){
             c.add(Calendar.DAY_OF_MONTH, 1);
         }

         Intent myIntent3 = new Intent(context, MyReceiver.class);
         n="2";
         myIntent3.putExtra("number", n);
         if(PendingIntent.getBroadcast(context, 2, 
                myIntent3, 
                PendingIntent.FLAG_NO_CREATE) == null){

         pendingIntent = PendingIntent.getBroadcast(context, 2, myIntent3,0);
         alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
         alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c3.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

      }
    }

}

在清单中:

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

...

 <receiver android:name="com.lp.lemiediete.MyReceiver">
     <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
    </receiver>

logcat的:

05-23 11:04:01.094: E/AndroidRuntime(5308): FATAL EXCEPTION: main
05-23 11:04:01.094: E/AndroidRuntime(5308): Process: com.lp.lemiediete, PID: 5308
05-23 11:04:01.094: E/AndroidRuntime(5308): java.lang.RuntimeException: Unable to start receiver com.lp.lemiediete.MyReceiver: java.lang.NullPointerException
05-23 11:04:01.094: E/AndroidRuntime(5308):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2426)
05-23 11:04:01.094: E/AndroidRuntime(5308):     at android.app.ActivityThread.access$1700(ActivityThread.java:135)
05-23 11:04:01.094: E/AndroidRuntime(5308):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
05-23 11:04:01.094: E/AndroidRuntime(5308):     at android.os.Handler.dispatchMessage(Handler.java:102)
05-23 11:04:01.094: E/AndroidRuntime(5308):     at android.os.Looper.loop(Looper.java:136)
05-23 11:04:01.094: E/AndroidRuntime(5308):     at android.app.ActivityThread.main(ActivityThread.java:5021)
05-23 11:04:01.094: E/AndroidRuntime(5308):     at java.lang.reflect.Method.invokeNative(Native Method)
05-23 11:04:01.094: E/AndroidRuntime(5308):     at java.lang.reflect.Method.invoke(Method.java:515)
05-23 11:04:01.094: E/AndroidRuntime(5308):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
05-23 11:04:01.094: E/AndroidRuntime(5308):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
05-23 11:04:01.094: E/AndroidRuntime(5308):     at dalvik.system.NativeStart.main(Native Method)
05-23 11:04:01.094: E/AndroidRuntime(5308): Caused by: java.lang.NullPointerException
05-23 11:04:01.094: E/AndroidRuntime(5308):     at com.lp.lemiediete.MyReceiver.onReceive(MyReceiver.java:25)
05-23 11:04:01.094: E/AndroidRuntime(5308):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2419)
05-23 11:04:01.094: E/AndroidRuntime(5308):     ... 10 more

1 个答案:

答案 0 :(得分:0)

您正在getStringExtra("number")的{​​{1}}上致电Intent。那个onReceive()没有额外的kety“数字”,所以这将返回Intent。然后,您将在此处获得null

NullPointerException

也许您想在此代码中调用 if(keyid.equals("0")){ 后添加return语句:

setAlarm()