Я разрабатываю приложение для молитв Android для мусульман. Я уже разработал код, чтобы получить время молитвы с помощью praytimes.org. Теперь я хочу сделать так, чтобы пользователь в то время был уведомлен о молитве. Но сейчас я просто хочу, чтобы вы могли отправить уведомление в определенное время. Если посмотреть на код и онлайн-ресурсы, мне кажется, что он должен работать, но по какой-то причине уведомление не отображается. Я знаю, что код для части уведомления правильный, потому что я создал кнопку для создания уведомления с использованием этого кода, и он работает. Поэтому я считаю, что проблема связана с сервисом, приемником или alarmManager.Уведомление в определенное время с использованием услуги
Я предполагаю, что проблема связана с методом onStartCommand() в MyNotificationService.java. Я не слишком хорошо знаком с услугами и их жизненными циклами, поэтому, пожалуйста, успокойся.
Заранее спасибо.
В моем MainActivity.java, вот код в моем методе onCreate().
/*========================Begin Notification Code==============================*/
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 1);
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.DAY_OF_MONTH, 18);
calendar.set(Calendar.HOUR_OF_DAY, 4);
calendar.set(Calendar.MINUTE, 45);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.PM);
Intent intent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
/*========================End Notification Code==============================*/
Вот MyReceiver.class
package com.ahmed.omar.tawheed;
/**
* Created by Omar on 1/18/15.
*/
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Intent service = new Intent(context, MyNotificationService.class);
context.startService(service);
}
}
Здесь MyNotificationService.java
package com.ahmed.omar.tawheed;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
public class MyNotificationService extends Service {
private NotificationManager notificationManager;
private int prayerNotificationID = 420; //blazeIt
@Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public int onStartCommand(Intent intent1, int flag, int startId) {
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification n = new NotificationCompat.Builder(this)
.setContentTitle("Time to Pray")
.setContentText("It is now time to pray salah")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
n.flags = Notification.FLAG_AUTO_CANCEL;
// Sending the notification itself
notificationManager.notify(prayerNotificationID, n);
return START_STICKY;
}
@Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Вот строки из моего AndroidManifest.xml
<service android:name=".MyNotificationService"
android:enabled="true" />
<receiver android:name=".MyReceiver"/>
Я гавань «Я внимательно посмотрел на ваш код, но, вообще говоря, я предпочитаю использовать сервисы с длинными сроками, такими как [Crontab.] (http://en.wikipedia.org/wiki/Cron). Он прост и хорошо понят и хорошо подходит для серверов , Все остальное имеет тенденцию изобретать колесо. – markspace
@markspace Учитывая, что я очень новичок в разработке Android, вы предлагаете мне использовать Crontab, а не просто сервис, чтобы ежедневно уведомлять пользователей о молитвенных временах? Это просто пояснение вашего комментария. –
О, я думал, что это серверная служба, а не что-то полностью работающее на мобильном устройстве. Извините, я не знаю, работает ли 'cron' на Android. – markspace