2015-08-03 14 views
1

Я пытаюсь запланировать локальные уведомления в своем приложении. Вот мой класс RootReceiver.Android: невозможно установить/получить данные с намерением

public class RebootReceiver extends BroadcastReceiver { 

private String EVENT_CATEGORY = "notification_event"; 

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

    Debug.waitForDebugger(); 
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
    Intent intent1 = new Intent(context, AlarmScheduler.class); 
    PendingIntent intentExecuted = PendingIntent.getBroadcast(context, 0, intent1, PendingIntent.FLAG_CANCEL_CURRENT); 
    Calendar now = Calendar.getInstance(); 

    if (!GeneralMethods.getBooleanPreference(context, ProperatiPreferences.APP_FIRST_LAUNCH)) { 
     intent1.putExtra(EVENT_CATEGORY, ""); 
     now.add(Calendar.HOUR, 2); 
     alarmManager.set(AlarmManager.RTC_WAKEUP, now.getTimeInMillis(), intentExecuted); 
    } else if (!GeneralMethods.getBooleanPreference(context, ProperatiPreferences.SEARCH_AFTER_THREE_DAYS)) { 
     intent1.putExtra(EVENT_CATEGORY, ""); 
     now.add(Calendar.DATE, 3); 
     alarmManager.set(AlarmManager.RTC_WAKEUP, now.getTimeInMillis(), intentExecuted); 
    } 
} 
} 

В здесь, как вы можете видеть, я хочу, чтобы создать намерение, в котором я хочу поставить некоторые данные (intent1). Однако намерение всегда пусто, без каких-либо дополнительных функций внутри него. Что я делаю не так?

Вот как я пытаюсь извлечь дополнительные данные из намерения.

public class AlarmScheduler extends BroadcastReceiver { 

private String EVENT_CATEGORY = "notification_event"; 

@Override 
public void onReceive(final Context context, final Intent intent) { 
    Log.d("com.properati.user", "AlarmScheduler.onReceive() called"); 

    Intent eventService = new Intent(context, AlarmService.class); 
    context.startService(eventService); 
} 

и, наконец, мой AlarmService класс:

public class AlarmService extends Service { 

private String EVENT_CATEGORY = "notification_event"; 

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

@Override 
public int onStartCommand(final Intent intent, final int flags, final int startId) { 
    Log.d("com.properati.user", "event received in service: " + new Date().toString()); 

    if(intent.getStringExtra(EVENT_CATEGORY).equals(ProperatiPreferences.APP_FIRST_LAUNCH)){ 
     new PushNotification(getApplicationContext()).scheduleNonOpenedNotification(getApplicationContext()); 
    }else if(intent.getStringExtra(EVENT_CATEGORY).equals(ProperatiPreferences.SEARCH_AFTER_THREE_DAYS)){ 
     new PushNotification(getApplicationContext()).scheduleNoSearchAfterThreeDays(getApplicationContext()); 
    } 

    return Service.START_NOT_STICKY; 
} 

ответ

1

Попробуйте следующий код в классе AlarmScheduler

public class AlarmScheduler extends BroadcastReceiver { 
    private String EVENT_CATEGORY = "notification_event"; 
@Override 
public void onReceive(final Context context, final Intent intent) { 
    Log.d("com.properati.user", "AlarmScheduler.onReceive() called"); 
    Intent eventService = new Intent(context, AlarmService.class); 
    eventService.putExtra(intent.getStringExtra(EVENT_CATEGORY, "")); 
    context.startService(eventService); 
} 
+1

Да мой друг это был правильный ответ. Мне не хватало, что дополнительные услуги не отправляются на третье мероприятие! Спасибо! – user5035668

0

после того, как я проверил источник PendingIntent в Android рамки, цель аргумент будет клонирован new Intent(intent). поэтому вам необходимо установить все данные на намерение1, прежде чем передавать его в конструктор PendingIntent.

@Override 
public IIntentSender getIntentSender(int type, 
     String packageName, IBinder token, String resultWho, 
     int requestCode, Intent[] intents, String[] resolvedTypes, 
     int flags, Bundle options, int userId) { 
    enforceNotIsolatedCaller("getIntentSender"); 
    // Refuse possible leaked file descriptors                                         
    if (intents != null) { 
     if (intents.length < 1) { 
      throw new IllegalArgumentException("Intents array length must be >= 1"); 
     } 
     for (int i=0; i<intents.length; i++) { 
      Intent intent = intents[i]; 
      if (intent != null) { 
       if (intent.hasFileDescriptors()) { 
        throw new IllegalArgumentException("File descriptors passed in Intent"); 
       } 
       if (type == ActivityManager.INTENT_SENDER_BROADCAST && 
         (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 
        throw new IllegalArgumentException(
          "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 
       } 
       intents[i] = new Intent(intent); 
      } 
     } 
     if (resolvedTypes != null && resolvedTypes.length != intents.length) { 
      throw new IllegalArgumentException(
        "Intent array length does not match resolvedTypes length"); 
     } 
    } 
+0

Даже никакого успеха намерения получить в службе сигнализации до сих пор пустой – user5035668

Смежные вопросы