2015-07-22 2 views
0

Я хотел бы отображать уведомление в определенное время и ежедневно (то есть в 8 часов утра). Я использую широковещательный приемник, будильник для отображения уведомлений. Но проблема в том, что я не получаю уведомления, отображаемые на мобильных устройствах. Я также добавил разрешения блокировки в файле манифеста. Помогите мне пожалуйста СпасибоОтображение уведомлений в определенное время

MainActivity.java

public class MainActivity extends ActionBarActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Calendar calendar = Calendar.getInstance(); 
    calendar.set(Calendar.HOUR_OF_DAY, 8); 
    calendar.set(Calendar.MINUTE, 00); 
    calendar.set(Calendar.SECOND, 0); 

    Intent notificationmassage = new Intent(getApplicationContext(),NotificationClass.class); 

    //This is alarm manager 
    PendingIntent pi = PendingIntent.getService(this, 0 , notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT); 
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); 
    am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 
      AlarmManager.INTERVAL_DAY, pi); 

    Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show(); 

} 

NotificationClass.java

public class NotificationClass extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 

     PendingIntent contentIntent = PendingIntent.getActivity(context, 0, 
       new Intent(context, MainActivity.class), 0); 

     NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) 
               .setSmallIcon(R.drawable.ic_launcher) 
               .setContentTitle("Text1") 
               .setContentText("Text2 "); 
     mBuilder.setContentIntent(contentIntent); 
     mBuilder.setDefaults(Notification.DEFAULT_SOUND); 
     mBuilder.setAutoCancel(true); 
     NotificationManager mNotificationManager ; 
     mNotificationManager= (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); 
     mNotificationManager.notify(1,mBuilder.build()); 

    } 
} 

манифеста:

<uses-sdk 
    android:minSdkVersion="8" 
    android:targetSdkVersion="21" /> 

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


<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

    <receiver android:name=".NotificationClass"> 
     </receiver> 
</application> 

Обновит E: - теперь возникли проблемы, когда я открываю уведомление приложения. Для Ex: Alarm Set to 8.AM, всякий раз, когда я открываю приложение после 8 часов утра, уведомление возникает ... даже если текущее время составляет> 8 AM. Как это решить?

ответ

1

В вашей деятельности Заменить следующие

PendingIntent pi = PendingIntent.getService(this, 0, notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT); 

с

PendingIntent pi = PendingIntent.getBroadcast(this, 0, notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT); 
+0

Хорошо. . Он показывает уведомление, когда я открываю приложение. Когда я закрою приложение, он не покажет его. Я думаю, что он не работает в фоновом режиме как процесс – Karan

+0

Как запустить его в качестве фонового процесса. Чтобы он отображал уведомления в определенное время, даже мое приложение закрыто? – Karan

+1

вы используете AlarmManager.RTC_WAKEUP, поэтому, как только вы вызываете am.setRepeating (...), он должен разбудить устройство в нужное время. Автоматически и с реализацией вашего приемника он должен отображать уведомление. – DaniZ

0
 public void getNotification(Context context,String Message){  
      int icon = R.drawable.appicon; 
      int when =(int) System.currentTimeMillis(); 
      NotificationManager notificationManager = (NotificationManager) 
        context.getSystemService(Context.NOTIFICATION_SERVICE); 
      Notification notification = new Notification(icon, Message, when); 

      String title = context.getString(R.string.app_name); 

      Intent notificationIntent = new Intent(context, MainActivity.class); 

      // set intent so it does not start a new activity 
      notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_CLEAR_TASK); 
      PendingIntent intent =PendingIntent.getActivity(context, 0, notificationIntent, 0); 
      notification.setLatestEventInfo(context, title,Message, intent); 
      notification.flags |= Notification.FLAG_AUTO_CANCEL; 

      // Play default notification sound 
      notification.defaults |= Notification.DEFAULT_SOUND; 

      // Vibrate if vibrate is enabled 
      notification.defaults |= Notification.DEFAULT_VIBRATE; 
      notificationManager.notify(0, notification); 

    } 
+0

Я хочу, чтобы отобразить уведомления на определенное время ежедневно или рутина, как @ 8'o часы в утро. Как это сделать? – Karan

+0

Как запустить его как фоновый процесс. Чтобы отображать уведомления в определенное время, даже мое приложение закрыто? – Karan

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