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

时间:2017-06-29 02:12:34

标签: java android android-intent broadcastreceiver alarmmanager

所以我从40天开始面对这个问题。试过eveything但没有任何工作。

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

逻辑是我发送2广播

每小时播放1次以检查小时值。如果小时值为1(即夜晚1 AM),则将brodcast接收器类设置为0,然后将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)
      }
    }
}

------------------------------------结束逻辑部分------- --------------

------------------------------------实际守则--------- ------------

我使用共享首选项变量在启动活动(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);
                    }
                }

-------------------------------------实际守则结束------ ------------------

现在的问题是,当我设置闹钟触发它每小时触发时,但只到晚上12点。假设我在上午9点30分设置闹钟,它将在10:00,11:00,12:00触发下午1点,下午1点,2:00,3:00,依此类推,直至凌晨12点,但之后停止触发。意味着它并不总是在凌晨1点 EVERYDAY 触发,以使notificationVariable为0。

抱歉我的英语不好。

1 个答案:

答案 0 :(得分:0)

完成将闹钟设置为在凌晨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;
}