java - 应用程序关闭时闹钟不起作用

标签 java android alarmmanager background-service

基本上,我正在尝试构建一个闹钟应用程序,其中有一些按钮以及一些预定义的日期和时间。我首先尝试过使用 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();
}
}

报警接收器.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();
}
}

最佳答案

您必须启动服务,然后它才能设置警报和火灾接收器

从你的 Activity 类开始这样

Intent intent=new Intent(this,MyService.class); 
startService(intent);

关于java - 应用程序关闭时闹钟不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50792419/

相关文章:

Android:无法取消重复闹钟

java - Spring JMSListener 和 JAXB 编码

conflict - java glassfish jdk 7 jre 6版本冲突

java - Struts2 Action 映射问题

android - 音频播放失败 - E/android.media.AudioTrack:多声道配置中必须存在前置声道

android - AlarmManager 不启动 BroadcastReceiver

java - ALOS 卫星产品到 PNG 转换问题(缺少旋转)

android - 如何在android中缓存和存储对象并设置过期策略?

android - 使用命令行重新同步 Gradle

android - 如何在特定日期和时间启动闹钟?