Java 每天第一次连接互联网时如何触发通知?

Java 每天第一次连接互联网时如何触发通知?,java,android,android-intent,broadcastreceiver,alarmmanager,Java,Android,Android Intent,Broadcastreceiver,Alarmmanager,所以我从40天开始就面临这个问题。什么都试过了,但什么都没用 ------------------------------------逻辑部分--------------------- 逻辑是我正在发送2个广播 1每小时广播一次以检查小时值。在brodcast receiver类中,如果小时值为1(即夜间1 AM),则将notificationVariable设置为0 1广播是指互联网连接时 if(internet connected ) { if(hour value

所以我从40天开始就面临这个问题。什么都试过了,但什么都没用

------------------------------------逻辑部分---------------------

逻辑是我正在发送2个广播

1每小时广播一次以检查小时值。在brodcast receiver类中,如果小时值为1(即夜间1 AM),则将notificationVariable设置为0

1广播是指互联网连接时

    if(internet connected )
   {
     if(hour value is between 7 to 22)
    { 
      if(notificationVariable ==0)
      {
        then trigger notification like Wallpaper of the day
        set the notificationVariable value to 1 ( so that it doesn't trigger on 2nd,3rd,4th time when internet is connected)
      }
    }
}
------------------------------------逻辑部分结束---------------------

------------------------------------实际代码---------------------

我正在使用共享首选项变量在Launching Acivity(MainActivity.java)中设置警报,以仅设置一次警报

pref = new PrefManager(getApplicationContext());
    if(pref.getSetAlarmOnce()==0) {
        setAlarm();
        pref.setSetAlarmOnce(1);
    }
下面的函数setAlarm是MainActivity.java文件中设置报警的代码

 public int setAlarm() {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Intent myIntent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() , AlarmManager.INTERVAL_HOUR, pendingIntent);
    return 0;
}
我使用setRepeating是因为setInexactRepeating根本没有触发报警

然后在广播接收机中

    Calendar rightNow = Calendar.getInstance();
    int currentHour = rightNow.get(Calendar.HOUR_OF_DAY);
   if(currentHour==1)
        {
            pref.setNotificationvariable(0);
            NotificationCompat.Builder builder2 = new NotificationCompat.Builder(arg0);
        int color2 = 0xff123456;
        Bitmap icon2 = BitmapFactory.decodeResource(arg0.getResources(), R.mipmap.ic_launcher);
        Notification notification2 = builder2 .setContentTitle("Notification Variable->"+pref.getNotificationvariable())
                .setContentText("Current Hour ->"+currentHour)
                .setColor(color2)
                .setAutoCancel(true)
                .setPriority(Notification.PRIORITY_HIGH)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(icon2)
                .build();
         NotificationManager notificationManager2 = (NotificationManager) arg0.getSystemService(arg0.NOTIFICATION_SERVICE);
        notificationManager2.notify(0, notification2);
    }

if (ConnectivityManager.CONNECTIVITY_ACTION.equals(arg1.getAction())) {
            NetworkInfo networkInfo = arg1.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
                if(currentHour>=7 && currentHour <=22)
                {
                    if(String.valueOf(pref.getNotificationvariable()).equals("0"))
                    {
                        notificationimages = new ArrayList<>();
                        albumsListreceiver=AppController.getInstance().getPrefManger().getCategories();
                        String albumId = albumsListreceiver.get(GenerateRandom(albumsListreceiver.size())).getId();
                        String url = "https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=481497b7c813f81b3fbf613f1c9783fb&photoset_id=" + albumId + "&user_id=153679059@N08&format=json";
                        Log.d("alarmreciever",url);
                        StringRequest getRequest1 = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                String s = response.replace("jsonFlickrApi(", "");
                                String snew = s.replace(")", "");
                                Log.d("alarmreciever","hi");
                                try {
                                    JSONObject jsonObject = new JSONObject(snew);
                                    JSONArray entry = jsonObject.getJSONObject("photoset").getJSONArray("photo");
                                    notificationimages.clear();
                                    Log.d("alarmreciever",String.valueOf(entry.length()));
                                    for (int i = 0; i < entry.length(); i++) {
                                        Log.d("alarmreciever","hi");
                                        JSONObject albumObj = (JSONObject) entry.get(i);
                                        Image image = new Image();
                                        String titleOfImage = albumObj.getString("title");
                                        image.setName(titleOfImage);
                                        String photoID = albumObj.getString("id");
                                        String secretID = albumObj.getString("secret");
                                        String farmID = albumObj.getString("farm");
                                        String serverID = albumObj.getString("server");
                                        String imageUrl = "https://farm" + farmID + ".staticflickr.com/" + serverID + "/" + photoID + "_" + secretID + "_b.jpg";
                                        image.setLarge(imageUrl);
                                        notificationimages.add(image);
                                    }
                                    int randompositionToShowImageinNotification=GenerateRandom(notificationimages.size());
                                    Intent notificationIntent = new Intent(arg0, FullScreenActivity.class);
                                    notificationIntent.putExtra("images",notificationimages);
                                    notificationIntent.putExtra("position", randompositionToShowImageinNotification);
                                    notificationIntent.putExtra("started_from","notification");
                                    PendingIntent pendingIntent= PendingIntent.getActivity(arg0,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
                                    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                    NotificationCompat.Builder builder = new NotificationCompat.Builder(arg0);
                                    int color = 0xff123456;
                                    Bitmap icon = BitmapFactory.decodeResource(arg0.getResources(), R.mipmap.ic_launcher);
                                    Notification notification = builder.setContentTitle("Pic of the Day")
                                            .setContentText("Tap this to get Your Pic of the Day Now !")
                                            .setColor(color)
                                            .setAutoCancel(true)
                                            .setSound(defaultSoundUri)
                                            .setPriority(Notification.PRIORITY_HIGH)
                                            .setSmallIcon(R.mipmap.ic_launcher)
                                            .setLargeIcon(icon)
                                            .setContentIntent(pendingIntent).build();
                                    NotificationManager notificationManager = (NotificationManager) arg0.getSystemService(arg0.NOTIFICATION_SERVICE);
                                    notificationManager.notify(0, notification);
                                    pref.setNotificationvariable(1);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                            }
                        });
                        // Remove the url from cache
                        AppController.getInstance().getRequestQueue().getCache().remove(url);
                        // Disable the cache for this url, so that it always fetches updated json
                        getRequest1.setShouldCache(false);
                        // Adding request to request queue
                        AppController.getInstance().addToRequestQueue(getRequest1);
                    }
                }
Calendar rightNow=Calendar.getInstance();
int currentHour=rightNow.get(Calendar.HOUR/OF\u DAY);
如果(当前小时==1)
{
pref.setNotificationvariable(0);
NotificationCompat.builder2=新的NotificationCompat.Builder(arg0);
int color2=0xff123456;
位图icon2=BitmapFactory.decodeResource(arg0.getResources(),R.mipmap.ic_启动器);
Notification notification2=builder2.setContentTitle(“通知变量->”+pref.getNotificationvariable())
.setContentText(“当前小时->”+当前小时)
.setColor(颜色2)
.setAutoCancel(真)
.setPriority(通知。优先级高)
.setSmallIcon(R.mipmap.ic_启动器)
.setLargeIcon(icon2)
.build();
NotificationManager notificationManager2=(NotificationManager)arg0.getSystemService(arg0.NOTIFICATION_服务);
notificationManager2.notify(0,notification2);
}
if(ConnectivityManager.CONNECTIVITY_ACTION.equals(arg1.getAction())){
NetworkInfo NetworkInfo=arg1.getParcelableExtra(ConnectivityManager.EXTRA\u NETWORK\u INFO);
if(networkInfo!=null&&networkInfo.getDetailedState()==networkInfo.DetailedState.CONNECTED){

如果(currentHour>=7&¤tHour,则将报警设置为在凌晨1:00触发,而不是每小时触发一次,并检查是否为凌晨1:00

改变了这个

public int setAlarm() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Intent myIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() , AlarmManager.INTERVAL_HOUR, pendingIntent);
return 0;
}

这个

public int setAlarm() {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 1);//this is the main change
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Intent myIntent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() , AlarmManager.INTERVAL_DAY, pendingIntent);
    return 0;
}