Java 通知可以在不遵循AlarmManager的情况下工作

Java 通知可以在不遵循AlarmManager的情况下工作,java,android,alarmmanager,Java,Android,Alarmmanager,我创建了两个不同的每日通知。两者都将在不同的给定时间运行。第二个通知将从API获取一些数据,检查来自该API的数据是否与今天的日期匹配,并显示它 每次我打开报警时,第一个通知都会运行(我已经创建了打开或关闭通知的设置),但它不会在给定的时间运行 另一个甚至不会运行BroadcastReceiver类,即使我已经设置了警报 这是我的密码 MainActivity.java public static void setAlarmDaily(Context context){ Calendar

我创建了两个不同的每日通知。两者都将在不同的给定时间运行。第二个通知将从API获取一些数据,检查来自该API的数据是否与今天的日期匹配,并显示它

每次我打开报警时,第一个通知都会运行(我已经创建了打开或关闭通知的设置),但它不会在给定的时间运行

另一个甚至不会运行BroadcastReceiver类,即使我已经设置了警报

这是我的密码

MainActivity.java

public static void setAlarmDaily(Context context){
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 7);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND,0);
    Intent intent = new Intent(context, NotifyService.class);
    intent.putExtra(EXTRA_TYPE, DAILY_REQUEST_CODE);
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context,100,intent,PendingIntent.FLAG_UPDATE_CURRENT);

    if(alarmManager != null){
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
    }
}

public static void setAlarmRelease(Context context){
    Intent intent = new Intent(context, NotifyService.class);
    intent.putExtra(EXTRA_TYPE, LATEST_REQUEST_CODE);
    AlarmManager alarmManager1 = (AlarmManager)context.getSystemService(ALARM_SERVICE);
    PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context,101,intent,PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar calendar1 = Calendar.getInstance();
    calendar1.set(Calendar.HOUR_OF_DAY, 8);
    calendar1.set(Calendar.MINUTE, 0);
    calendar1.set(Calendar.SECOND,0);

    if(alarmManager1 != null){
        alarmManager1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent1);
    }
}
@Override
public void onReceive(final Context context, Intent intent) {
    int type = intent.getIntExtra(EXTRA_TYPE, 101);

    if(type==100){
        showNotificationDaily(context);
    }else {
        final PendingResult pendingResult = goAsync();
        Thread thread = new Thread(){
            public void run(){
                AsyncHttpClient client = new AsyncHttpClient();
                client.get(url, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        try {
                            ArrayList<Movie> listMov = null;
                            String result = new String(responseBody);
                            JSONObject responseObject = new JSONObject(result);
                            JSONArray results = responseObject.getJSONArray("results");

                            for (int i = 0; i < results.length(); i++) {
                                int id = results.getJSONObject(i).getInt("id");
                                String title = results.getJSONObject(i).getString("title");
                                String releaseDate = results.getJSONObject(i).getString("release_date");

                                Movie mov = new Movie();
                                mov.setId(id);
                                mov.setTitle(title);
                                mov.setReleaseDate(releaseDate);
                                listMov.add(mov);
                            }
                            listMovie = listMov;
                            pendingResult.finish();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                    }
                });
            }
        };
        thread.start();

        ArrayList<Movie> movies = listMovie;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        Date date = new Date();
        String now = dateFormat.format(date);
        for(Movie movieItem : movies){
            if(movieItem.getReleaseDate().equals(now)){
                showNotificationRelease(context, movieItem.getId(), movieItem.getTitle());
                Log.d(TAG,movieItem.getReleaseDate());
            }
        }
    }
}

public void showNotificationRelease(Context context, int id, String title){
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationManager notificationManager2 = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
    Intent i = new Intent(context, DetailActivity.class);
    Movie movie = new Movie();
    movie.setId(id);
    movie.setTitle(title);
    movie.setType("movie");
    i.putExtra(DetailActivity.EXTRA_DETAIL,movie);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pIntent2 = PendingIntent.getActivity(context, 101, i, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder notification2 = new Notification.Builder(context)
            .setContentIntent(pIntent2)
            .setContentTitle(context.getString(R.string.release_now_string))
            .setContentText(title + context.getString(R.string.has_release_string))
            .setSmallIcon(R.drawable.ic_live_tv_black_24dp)
            .setSound(sound)
            .setAutoCancel(true);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel dailyNotificationChannel = new NotificationChannel("101",
                "Latest",
                NotificationManager.IMPORTANCE_DEFAULT);

        dailyNotificationChannel.enableVibration(true);
        dailyNotificationChannel.setVibrationPattern(new long[]{1000, 1000, 1000, 1000, 1000});

        notification2.setChannelId("100");

        if(notificationManager2 != null){
            notificationManager2.createNotificationChannel(dailyNotificationChannel);
        }
    }

    if(notificationManager2 != null){
        notificationManager2.notify(101, notification2.build());
    }
}

public void showNotificationDaily(Context context){
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationManager notificationManager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
    Intent i = new Intent(context, MainActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pIntent = PendingIntent.getActivity(context, 100, i, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder notification = new Notification.Builder(context)
            .setContentIntent(pIntent)
            .setContentTitle(context.getString(R.string.good_morning_string))
            .setContentText(context.getString(R.string.check_app_string))
            .setSmallIcon(R.drawable.ic_movie_black_24dp)
            .setSound(sound)
            .setAutoCancel(true);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel dailyNotificationChannel = new NotificationChannel("100",
                "Daily",
                NotificationManager.IMPORTANCE_DEFAULT);

        dailyNotificationChannel.enableVibration(true);
        dailyNotificationChannel.setVibrationPattern(new long[]{1000, 1000, 1000, 1000, 1000});

        notification.setChannelId("100");

        if(notificationManager != null){
            notificationManager.createNotificationChannel(dailyNotificationChannel);
        }
    }

    if(notificationManager != null){
        notificationManager.notify(100, notification.build());
    }
}
NotifyService.java

public static void setAlarmDaily(Context context){
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 7);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND,0);
    Intent intent = new Intent(context, NotifyService.class);
    intent.putExtra(EXTRA_TYPE, DAILY_REQUEST_CODE);
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context,100,intent,PendingIntent.FLAG_UPDATE_CURRENT);

    if(alarmManager != null){
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
    }
}

public static void setAlarmRelease(Context context){
    Intent intent = new Intent(context, NotifyService.class);
    intent.putExtra(EXTRA_TYPE, LATEST_REQUEST_CODE);
    AlarmManager alarmManager1 = (AlarmManager)context.getSystemService(ALARM_SERVICE);
    PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context,101,intent,PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar calendar1 = Calendar.getInstance();
    calendar1.set(Calendar.HOUR_OF_DAY, 8);
    calendar1.set(Calendar.MINUTE, 0);
    calendar1.set(Calendar.SECOND,0);

    if(alarmManager1 != null){
        alarmManager1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent1);
    }
}
@Override
public void onReceive(final Context context, Intent intent) {
    int type = intent.getIntExtra(EXTRA_TYPE, 101);

    if(type==100){
        showNotificationDaily(context);
    }else {
        final PendingResult pendingResult = goAsync();
        Thread thread = new Thread(){
            public void run(){
                AsyncHttpClient client = new AsyncHttpClient();
                client.get(url, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        try {
                            ArrayList<Movie> listMov = null;
                            String result = new String(responseBody);
                            JSONObject responseObject = new JSONObject(result);
                            JSONArray results = responseObject.getJSONArray("results");

                            for (int i = 0; i < results.length(); i++) {
                                int id = results.getJSONObject(i).getInt("id");
                                String title = results.getJSONObject(i).getString("title");
                                String releaseDate = results.getJSONObject(i).getString("release_date");

                                Movie mov = new Movie();
                                mov.setId(id);
                                mov.setTitle(title);
                                mov.setReleaseDate(releaseDate);
                                listMov.add(mov);
                            }
                            listMovie = listMov;
                            pendingResult.finish();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                    }
                });
            }
        };
        thread.start();

        ArrayList<Movie> movies = listMovie;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        Date date = new Date();
        String now = dateFormat.format(date);
        for(Movie movieItem : movies){
            if(movieItem.getReleaseDate().equals(now)){
                showNotificationRelease(context, movieItem.getId(), movieItem.getTitle());
                Log.d(TAG,movieItem.getReleaseDate());
            }
        }
    }
}

public void showNotificationRelease(Context context, int id, String title){
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationManager notificationManager2 = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
    Intent i = new Intent(context, DetailActivity.class);
    Movie movie = new Movie();
    movie.setId(id);
    movie.setTitle(title);
    movie.setType("movie");
    i.putExtra(DetailActivity.EXTRA_DETAIL,movie);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pIntent2 = PendingIntent.getActivity(context, 101, i, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder notification2 = new Notification.Builder(context)
            .setContentIntent(pIntent2)
            .setContentTitle(context.getString(R.string.release_now_string))
            .setContentText(title + context.getString(R.string.has_release_string))
            .setSmallIcon(R.drawable.ic_live_tv_black_24dp)
            .setSound(sound)
            .setAutoCancel(true);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel dailyNotificationChannel = new NotificationChannel("101",
                "Latest",
                NotificationManager.IMPORTANCE_DEFAULT);

        dailyNotificationChannel.enableVibration(true);
        dailyNotificationChannel.setVibrationPattern(new long[]{1000, 1000, 1000, 1000, 1000});

        notification2.setChannelId("100");

        if(notificationManager2 != null){
            notificationManager2.createNotificationChannel(dailyNotificationChannel);
        }
    }

    if(notificationManager2 != null){
        notificationManager2.notify(101, notification2.build());
    }
}

public void showNotificationDaily(Context context){
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationManager notificationManager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
    Intent i = new Intent(context, MainActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pIntent = PendingIntent.getActivity(context, 100, i, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder notification = new Notification.Builder(context)
            .setContentIntent(pIntent)
            .setContentTitle(context.getString(R.string.good_morning_string))
            .setContentText(context.getString(R.string.check_app_string))
            .setSmallIcon(R.drawable.ic_movie_black_24dp)
            .setSound(sound)
            .setAutoCancel(true);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel dailyNotificationChannel = new NotificationChannel("100",
                "Daily",
                NotificationManager.IMPORTANCE_DEFAULT);

        dailyNotificationChannel.enableVibration(true);
        dailyNotificationChannel.setVibrationPattern(new long[]{1000, 1000, 1000, 1000, 1000});

        notification.setChannelId("100");

        if(notificationManager != null){
            notificationManager.createNotificationChannel(dailyNotificationChannel);
        }
    }

    if(notificationManager != null){
        notificationManager.notify(100, notification.build());
    }
}
@覆盖
公共void onReceive(最终上下文、意图){
int type=intent.getIntExtra(额外类型,101);
如果(类型==100){
showNotificationDaily(上下文);
}否则{
最终Pendingreult Pendingreult=goAsync();
线程线程=新线程(){
公开募捐{
AsyncHttpClient=新的AsyncHttpClient();
get(url,新的AsyncHttpResponseHandler(){
@凌驾
成功时的公共void(int statusCode,Header[]headers,byte[]responseBody){
试一试{
ArrayList listMov=null;
字符串结果=新字符串(responseBody);
JSONObject responseObject=新JSONObject(结果);
JSONArray结果=responseObject.getJSONArray(“结果”);
对于(int i=0;i=Build.VERSION\u code.O){
NotificationChannel dailyNotificationChannel=新的NotificationChannel(“101”,
“最新”,
NotificationManager.重要性(默认值);
dailyNotificationChannel.启用振动(真);
设置振动模式(新的长[]{1000,1000,1000,1000,1000});
通知2.setChannelId(“100”);
如果(notificationManager2!=null){
notificationManager2.createNotificationChannel(dailyNotificationChannel);
}
}
如果(notificationManager2!=null){
notificationManager2.notify(101,notification2.build());
}
}
public void showNotificationDaily(上下文){
Uri sound=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_通知);
NotificationManager NotificationManager=(NotificationManager)context.getSystemService(context.NOTIFICATION\u服务);
意图i=新意图(上下文,MainActivity.class);
i、 设置标志(意图、标志、活动、清除、顶部);
PendingEvent pIntent=PendingEvent.getActivity(上下文,100,i,PendingEvent.FLAG_UPDATE_CURRENT);
Notification.Builder Notification=new Notification.Builder(上下文)
.setContentIntent(pIntent)
.setContentTitle(context.getString(R.string.good_morning_string))
.setContentText(context.getString(R.string.check\u app\u string))
.setSmallIcon(R.drawable.ic_movie_black_24dp)
.setSound(声音)
.setAutoCancel(真);
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.O){
NotificationChannel dailyNotificationChannel=新的NotificationChannel(“100”,
“每日”,
NotificationManager.重要性(默认值);
每日通知
 long dateTime = calendar.getTimeInMillis();
 if (dateTime <= System.currentTimeMillis()) {
     time = dateTime + 24 * 3600 * 1000;
 } 
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setWindow(AlarmManager.RTC_WAKEUP, dateTime ,
                AlarmManager.INTERVAL_DAY, pendingIntent);
    } else {
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, dateTime , 
                AlarmManager.INTERVAL_DAY, pendingIntent);
    }
long dateTime = calendar.getTimeInMillis();
 if (dateTime <= System.currentTimeMillis()) {
     time = dateTime + 24 * 3600 * 1000;
 } 
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        //alarmManager.setExact(AlarmManager.RTC_WAKEUP, dateTime, pendingIntent); // not suggested
        // 15 mins of window to call the alarm and have battery optimization
        long windowMillis = 15 * 60 * 1000L;
        alarmManager.setWindow(AlarmManager.RTC_WAKEUP, dateTime ,
                windowMillis, pendingIntent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, dateTime, pendingIntent);
    }