如何在每天第一次连接互联网时触发通知?
How to trigger notification when internet is connected for the first time on each day?
所以我从 40 天开始就面临这个问题。尝试了一切,但没有任何效果。
------------------------------------逻辑部分------ --------------
逻辑是我发送2个广播
每小时广播 1 次以检查小时值。在广播接收器中 class 如果小时值为 1(即晚上 1 点),则将 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 Acvitivity(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 PM,1:00PM,2:00,3:00 等等,直到晚上 12:00 AM,但之后它停止触发。意味着它并不总是在 1:00 AM EVERYDAY 触发,使 notificationVariable 变为 0 。
抱歉我的英语不好。
通过将警报设置为在 1:00 AM 触发而不是每小时触发并检查是否是 1:00 AM 来完成。
改变了这个
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;
}
所以我从 40 天开始就面临这个问题。尝试了一切,但没有任何效果。
------------------------------------逻辑部分------ --------------
逻辑是我发送2个广播
每小时广播 1 次以检查小时值。在广播接收器中 class 如果小时值为 1(即晚上 1 点),则将 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 Acvitivity(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 PM,1:00PM,2:00,3:00 等等,直到晚上 12:00 AM,但之后它停止触发。意味着它并不总是在 1:00 AM EVERYDAY 触发,使 notificationVariable 变为 0 。
抱歉我的英语不好。
通过将警报设置为在 1:00 AM 触发而不是每小时触发并检查是否是 1:00 AM 来完成。
改变了这个
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;
}