Будильник не работает, когда приложение закрыто

По сути, я пытаюсь создать приложение для будильника, в котором есть несколько кнопок с предопределенными датой и временем. Сначала я пытался использовать AlarmManager и широковещательный приемник, но это не сработало. Итак, я использовал службу переднего плана с alarmManager, но, тем не менее, сигнал тревоги не срабатывает, когда приложение уничтожается. Я новичок. Я пытался искать в Интернете, но мне не повезло. Надеюсь, тут много людей, которые помогут мне. Заранее спасибо.

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

AndroidManifest.xml

 <receiver android:name=".AlarmReceiver" />

    <activity
        android:name=".Activity.PlayerDetailsActivity"
        android:theme="@style/AppTheme.NoActionBar"></activity>
    <activity android:name=".Activity.FixtureActivity" />

    <service android:name=".MyService"/>

MyService.java

public class MyService extends Service {
public MyService() {
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Toast.makeText(this, "Started", Toast.LENGTH_SHORT).show();
    Log.e("service","service");
    long longExtra = intent.getLongExtra(Constants.ALARM_TIME, 0000);

    //Testing Area Start
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(longExtra);

    int mMin = calendar.get(Calendar.MINUTE);
    int mMonth = calendar.get(Calendar.MONTH);
    int mDay = calendar.get(Calendar.DAY_OF_MONTH);
    int mHour = calendar.get(Calendar.HOUR_OF_DAY);

    Log.e("hour min month day"," "+mHour + " : "+mMin+" month : "+mMonth+" "+" Date : "+mDay+" ");
    String currentDateTime=getDeviceDateTime();
    Log.e("CurrentdateTime",""+currentDateTime);


    Log.e("longExtra",""+longExtra);
    //Testing Area End

        String CHANNEL_ID = "my_channel_01";
    NotificationChannel channel = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        channel = new NotificationChannel(CHANNEL_ID,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT);

    ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("dfdf")
                .setSmallIcon(R.drawable.ic_notifications_black_24dp)
                .setContentText("dfdfd").build();
        startForeground(3, notification);
    }

    /*Intent alertIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    Log.d("I",""+longExtra);
    alarmManager.set(AlarmManager.RTC_WAKEUP, 6000000, PendingIntent.getBroadcast(getApplicationContext(), 0, alertIntent,
            PendingIntent.FLAG_ONE_SHOT));*/

    AlarmManager manager= (AlarmManager)getSystemService(ALARM_SERVICE);
    Intent myIntent;
    myIntent = new Intent(getApplicationContext(),AlarmReceiver.class);
    myIntent.putExtra("check",true);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,0);
    Long finalTime =longExtra-System.currentTimeMillis();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        manager.setExact(AlarmManager.RTC_WAKEUP,longExtra,pendingIntent);
    }
    else
        manager.set(AlarmManager.RTC_WAKEUP,longExtra,pendingIntent);


    return START_NOT_STICKY;
}





@Override
public void onDestroy() {
    super.onDestroy();
}
}

Alarmreceiver.java

 public class AlarmReceiver extends BroadcastReceiver
{
public static final String CHANNEL_ID = "47";
@Override
public void onReceive(Context context, Intent intent)
{
    intent = new Intent(context, SplashActivity.class);
    intent.putExtra("not",true);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);


    NotificationCompat.Builder notificationCompat = new NotificationCompat.Builder(context,CHANNEL_ID);
    notificationCompat.setSmallIcon(R.drawable.ic_notifications_black_24dp);
    notificationCompat.setContentTitle("My Noticiation");
    notificationCompat.setContentText(getPreferences(context).getDateTime());
    notificationCompat.setContentIntent(pendingIntent);
    notificationCompat.setSound(alarmSound);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "channel name", importance);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }

    Notification notification = notificationCompat.build();

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
    notificationManager.notify(100,notification);
    Toast.makeText(context, "Alarm Working", Toast.LENGTH_SHORT).show();
}
}

person Shakib Uz-Zaman    schedule 11.06.2018    source источник
comment
вам может понадобиться блокировка пробуждения в службе   -  person Sanjay Kumar    schedule 11.06.2018
comment
любое решение сработало для вас?   -  person Ahmad    schedule 06.07.2020


Ответы (4)


вы должны запустить свою службу, чтобы она могла установить сигнализацию и пожарный приемник

начните это так из своего класса активности

Intent intent=new Intent(this,MyService.class); 
startService(intent);
person ramzi tannous    schedule 11.06.2018
comment
Служба работает нормально, когда приложение запущено. Он также показывает тревогу соответственно. но служба не работает, когда приложение закрыто. - person Shakib Uz-Zaman; 11.06.2018

Рассмотрите возможность использования JobScheduler в качестве механизма сохраняемости. Он бодрствует и обрабатывает блокировку пробуждения за вас. Единственный недостаток для Android SDK >= 21 (Lollipop). Также в городе появился новый друг, который сделает для вас обратную совместимость: WorkManager. и будет работать со всеми версиями Android, даже ниже Lollipop.

person Arseny Levin    schedule 11.06.2018
comment
Спасибо за информацию. Я попробую и поделюсь, если это сработает. - person Shakib Uz-Zaman; 11.06.2018

Intent myIntent;
    myIntent = new Intent(this, AlarmReceiver.class);
    myIntent.putExtra("check",true);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);

==============================
Не могли бы вы изменить приведенный выше код следующим образом?

Intent myIntent;

myIntent = new Intent(this , MyService.class);

myIntent.setAction("REQUEST_FROM_ALARM_MANAGER");

PendingIntent pendingIntent = PendingIntent.getForegroundService(this,0,myIntent,0);

================================================== ==
И класс обслуживания

@RequiresApi(api = Build.VERSION_CODES.O)

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

    mContext = this;

    Log.e(TAG, "onStartCommand " + intent);

    if(intent == null) {
        return START_NOT_STICKY;
    }

    if("REQUEST_FROM_ALARM_MANAGER".equals(intent.getAction())){
        // show Notification here for your foreground service

    }
    return START_NOT_STICKY;
 } 
person Jitendra    schedule 10.05.2020

Вы должны запустить службу, которая выживет в вашем приложении, вы можете увидеть здесь как это сделать

person TheOni    schedule 11.06.2018
comment
Я уже воспользовался услугой. Пожалуйста, смотрите второй блок кода. - person Shakib Uz-Zaman; 11.06.2018