I Made the Notification part in my developing mobile application. It's working perfectly in kitkat down versions as well as upper versions but oreo version. Oreo version it's not trigger the notification. what is the reason.. Following are my codes..
Alert Activity
List<Time> times = new ArrayList<>();
times.add(new Time(hour, mminute));
Intent intent = new Intent(this, MyBroadcastReceiver.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
for (Time time : times) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), broadcastCodeCus++, intent, 0);
Calendar cal_alarm = Calendar.getInstance();
cal_alarm.set(Calendar.HOUR_OF_DAY, Integer.valueOf(hour));
cal_alarm.set(Calendar.MINUTE, Integer.valueOf(mminute));
cal_alarm.set(Calendar.SECOND, 00);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), pendingIntent);
Toast.makeText(this, "Alarm > KITKAT & Alarm Set For: " + hour + " : " + mminute, Toast.LENGTH_SHORT).show();
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
alarmManager.set(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), pendingIntent);
Toast.makeText(this, "Alarm < KITKAT & Alarm Set For: " + hour + " : " + mminute, Toast.LENGTH_SHORT).show();
}
customText.append(broadcastCodeCus + ". " + time.hour + ":" + time.minute + "\n");
}
MyBroadcastReceiver
NotificationManager notificationManager=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent= new Intent(context,secondActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent= PendingIntent.getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context,CHANNEL_ID)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.drink)
.setContentTitle(textTitle)
.setContentText(textContent)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(textContent))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH) // >=API level 21
.setLights(Color.WHITE, 2000, 3000)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); // >=API level 21
notificationManager.notify(100,mBuilder.build());
}
In Android Oreo, it's a must to use a channel with your Notification Builder
you can follow the following code for the Notification Channel..
// Sets an ID for the notification, so it can be updated.
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
.setChannelId(CHANNEL_ID)
.build();
Related
can anyone help me out on how to use speech recognition to listen right after porcupine wake up word. We need to some how figure out how to stop porcupine manager from listening the microphone until speech recognition is done listening to it.
try {
Log.i("YOU SAID IT!", "yesss");
porcupineManager = new PorcupineManager.Builder()
.setKeyword(Porcupine.BuiltInKeyword.JARVIS)
.setSensitivity(0.7f).build(
getApplicationContext(),
(keywordIndex) -> {
// This is where I need to somehow stop so that I can trigger speech recognition to listen
numUtterances++;
PendingIntent contentIntent = PendingIntent.getActivity(
this,
0,
new Intent(this, MainActivity.class),
0);
final String contentText = numUtterances == 1 ? " time!" : " times!";
Notification n = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Wake word")
.setContentText("Detected " + numUtterances + contentText)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(contentIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(1234, n);
});
porcupineManager.start();
} catch (PorcupineException e) {
Log.e("PORCUPINE", e.toString());
}
For my app, I should send notifications to user.
For example:
user set 3 notifications
12:00
18:00
08:00
I want to send each notification everyday until i cancel them individually. Notifications should be sent, even if the app is closed.
Main:
registerAlarm(12, 0, 1);
registerAlarm(18, 0, 2);
registerAlarm(8, 0, 3);
Main Methods:
private PendingIntent registerAlarm(int hour, int minute, int id){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
intent.putExtra("NAME",id);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, id, intent,0);
AlarmManager am = (AlarmManager)this.getSystemService(this.ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
System.out.println("SELAMLAR OLSUN ID MAIN: " + id);
return pendingIntent;
}
private void cancelAlarm(int RSQ) {
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RSQ, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
Alarm Reciever:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent("com.demo.FirebaseMessagingReceiveService");
notificationIntent.setClass(context, Main2Activity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int id = Integer.valueOf(intent.getStringExtra("NAME"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, id, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification.Builder builder = new Notification.Builder(context)
.setSmallIcon(R.drawable.ic_android_black_24dp)
.setContentTitle("ONLINE QUIZ APP")
.setContentText("HEY TRY TO SOLVE TODAY")
.setSound(alarmSound)
.setAutoCancel(true)
.setWhen(when)
.setContentIntent(pendingIntent)
.setVibrate(new long[] {1000, 1000, 1000, 1000, 1000});
context.startService(notificationIntent);
notificationManager.notify(id, builder.build());
}
}
intent.putExtra("NAME",id);
int id = Integer.valueOf(intent.getStringExtra("NAME"));
don't working, ignore them.
The below class is used in an array.
package com.example.ShivitoMGO;
public class RoomTable {
public String RoomName,UpDown,minmaxint;
}
Main Activity
static ArrayList <RoomTable> CountCheck = new ArrayList<>();
public void playerup(View vvv){
st_spinner = v1.findViewById(R.id.spinner);
st_reportLayout = v1.findViewById(R.id.reportlayout);
st_Leanervidimg = v1.findViewById(R.id.Linearvidcopy);
TextView roomname = v1.findViewById(R.id.action_Players1);
RoomTable roomtb = new RoomTable();
if (CountCheck.size() == 0){
//playerupdown = "up";
Toast.makeText(this, "Will notify when " + mRooms.get(position1) + " players increase #" + mRoomSize.get(position1), Toast.LENGTH_LONG).show();
String[] minmaxval = mRoomSize.get(position1).split("/");
CountCheckint = Integer.parseInt(minmaxval[0].trim());
//CountCheck = (String) mRooms.get(position1);
roomtb.RoomName = (String) mRooms.get(position1);
roomtb.minmaxint = minmaxval[0].trim();
roomtb.UpDown = "up";
Log.d("added: ", "it was added");
CountCheck.add(roomtb);
Log.d("RoomTableadd: ",roomtb.RoomName+ " " + roomtb.minmaxint +" " +roomtb.UpDown);
st_reportLayout.setVisibility(View.GONE);
Log.d("Longclickhere: ", mRoomSize.get(position1));
Log.d("RoomNameCount ", String.valueOf(CountCheck.get(0).RoomName));
}else {
int exist1 = 0;
int poss;
for (int i = 0; i < CountCheck.size(); i++) {
if (roomname.getText() == CountCheck.get(i).RoomName) {
Log.d("RoomNametxt: " , CountCheck.get(i).RoomName);
Log.d("RoomNametxt: ", (String) roomname.getText());
Toast.makeText(this, "Notification " + CountCheck.get(i).RoomName + " OFF!", Toast.LENGTH_LONG).show();
Log.d("Removed item: ", String.valueOf(CountCheck.size()));
CountCheck.remove(i);
Log.d("Removed item: ", String.valueOf(CountCheck.size()));
st_reportLayout.setVisibility(View.GONE);
exist1 = 1;
poss = i;
} else {
exist1 = 0;
}
}
if (exist1 == 0) {
Toast.makeText(this, "Will notify when " + mRooms.get(position1) + " players increase #" + mRoomSize.get(position1), Toast.LENGTH_LONG).show();
String[] minmaxval = mRoomSize.get(position1).split("/");
CountCheckint = Integer.parseInt(minmaxval[0].trim());
//CountCheck = (String) mRooms.get(position1);
roomtb.RoomName = (String) mRooms.get(position1);
roomtb.minmaxint = minmaxval[0].trim();
roomtb.UpDown = "up";
Log.d("added: ", "it was added");
CountCheck.add(roomtb);
Log.d("RoomTableadd: ", roomtb.RoomName + " " + roomtb.minmaxint + " " + roomtb.UpDown);
st_reportLayout.setVisibility(View.GONE);
}
Log.d("CountSize: ", String.valueOf(CountCheck.size()));
for (int xb = 0;xb<CountCheck.size();xb++) {
try {
Log.d("RoomNameCount ", String.valueOf(CountCheck.get(xb).RoomName));
} catch (Exception e) {
Log.d("Out of range ", String.valueOf(e));
}
}
}
}
Recycler-View
#Override
public boolean onLongClick(View v) {
// Launch your web intent
if (CountCheck.size() != 0){
Log.d("Longclickhere: ",mRoomSize.get(position));
Toast.makeText(mContext, mRoomSize.get(position), Toast.LENGTH_SHORT).show();
Toast.makeText(mContext, "Will notify when "+mRooms.get(position)+" players decrease", Toast.LENGTH_SHORT).show();
String[] minmaxval = mRoomSize.get(position).split("/");
MainActivity.CountCheckint = Integer.parseInt(minmaxval[0].trim());
} else{
//MainActivity.CountCheck = "";
Toast.makeText(mContext, "Player Decrease notification OFF", Toast.LENGTH_SHORT).show();
}
return true;
In this app the recycler view creates the "rooms" and if the room is selected the textview and 2 other values are put in to the RoomTable. these are stored and used in a service to check if ether of the other to values change. Everything works as intended unless i use the swip-to-refresh witch runs the recycler-view again. If i do not refresh and i select the same item in the recycler-view it will remove it from CountCheck . However if i run the refresh and select the same recycler-view item that i selected previously it will add it instead of removing it. This Makes no since to me because i use a for loop to Check the CountCheck.get(i).RoomName aka the textview and if the names are the same then my if statement will remove instead of add. is it somehow possible i'm ending up with 2 CountCheck Objects????? with the same name???? Please I'm out of ideas on this one. Thanks.
I dont remember why. Maybe someone can explain but i changed this line
if (roomname.getText() == CountCheck.get(i).RoomName)
To this
if (roomname.getText().equals(CountCheck.get(i).RoomName));
and that fixed the issue. please let me know the difference if you are reading this.
How can I make the download of emails from GMAIL faster, using IMAP and JavaMail?
Can I do bulk download using IMAP?
I am saving the emails into MongoDB as well.
I saw some websites are doing it very quickly.
Are there any performance tips that I can use here.
-----------------------------------------------------
// Get inbox folder
Folder inbox = store.getFolder("inbox");
// SET readonly format (*You can set read and write)
inbox.open(Folder.READ_ONLY);
// Display email Details
// Inbox email count
int messageCount = inbox.getMessageCount();
System.out.println("Total Messages in INBOX:- " + messageCount);
Message[] messages = inbox.getMessages(1, messageCount);
long startTime = System.currentTimeMillis();
// Fetch only necessary headers for each message
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
profile.add(FetchProfile.Item.FLAGS);
profile.add(FetchProfile.Item.CONTENT_INFO);
if (inbox instanceof UIDFolder) {
profile.add(UIDFolder.FetchProfileItem.UID);
}
inbox.fetch(messages, profile);
System.out
.println("Time elapsed while fetching message headers;" + (System.currentTimeMillis() - startTime));
ArrayList<Email> al = new ArrayList<Email>();
for (int i = 1; i < messageCount; i++) {
//System.out.println("------------------------------------------------------------");
Email email = new Email();
email.setId(i + "");
email.setSenderAddress(extractEmail(messages[i].getFrom()[0].toString()));
email.setReceivedDate(messages[i].getReceivedDate());
email.setSentDate(messages[i].getSentDate());
email.setSubject(messages[i].getSubject());
email.setMessageContent(messages[i].getContent().toString());
email.setReceiverAddresses(new String[messages[i].getAllRecipients().length]);
for (int j = 0; j < messages[i].getAllRecipients().length; j++)
email.getReceiverAddresses()[j] = extractEmail(
messages[i].getAllRecipients()[j].toString());
al.add(email);
if (i % 2000 == 0) {
emailMongoRepository.save(al);
System.out.println("----------Bulk Save--------------------------------------------------");
al = new ArrayList<Email>();
}
}
inbox.close(true);
store.close();
System.out.println("Time elapsed while fetching message headers;" + (System.currentTimeMillis() - startTime));
} catch (Exception e) {
e.printStackTrace();
}
I am trying to register device token with tag in azure push notification hub in development mode but in azure portal it shows 0 active devices registered, when I check with notification hub it will show one registration is occur.
Here is my sample code:
App delegate:
var deviceTokenDes = deviceToken.Description;
if (!string.IsNullOrWhiteSpace(deviceTokenDes))
{
deviceTokenDes = deviceTokenDes.Trim('<');
deviceTokenDes = deviceTokenDes.Trim('>');
deviceTokenDes = deviceTokenDes.Replace(" ", "");
DeviceToken = deviceTokenDes.Trim('<');
DeviceToken = deviceTokenDes.Trim('>');
DeviceToken = deviceTokenDes.Replace(" ", "");
}
Hub = new SBNotificationHub(myapp.ListenConnectionString, myapp.NotificationHubName);
Login view model:
var tags = new List<string> { userId };
AppDelegate.Hub?.UnregisterAllAsync(AppDelegate.DeviceToken, error =>
{
if (error != null)
{
Console.WriteLine("Error calling Unregister: {0}", error);
}
AppDelegate.Hub.RegisterNativeAsync(AppDelegate.DeviceToken, new NSSet(tags.ToArray()), errorCallback =>
{
if (errorCallback != null)
{
Console.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
}
});
I have registered device token with tag after user successfully login in to the application. Can you please suggest idea on.
This is all we do in our AppDelegate class.
public override async void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
bool ShouldComplete = true;
// Validate if we have already got a registration
try
{
string validation = NSUserDefaults.StandardUserDefaults.StringForKey("InitialTagRegistration");
if (validation.Contains("Completed"))
{
ShouldComplete = false;
}
}
catch (Exception genEx)
{
ApplicationLog.AppendFile(DateTime.Now.ToString() + " : " + "[EXCEPTION] - Exception has been hit! - Message: " + genEx.Message + " | Source: " + genEx);
}
Hub = new SBNotificationHub(ConfigurableSettings.NotificationHubConnectionString, ConfigurableSettings.NotificationHubPathName);
ApplicationState.SetValue("NotificationHub", Hub);
// Get previous device token
NSData oldDeviceToken = await ApplicationSettings.RetrieveDeviceToken();
// If the token has changed unregister the old token and save the new token to UserDefaults.
if (oldDeviceToken != null)
{
if (oldDeviceToken.ToString() != deviceToken.ToString())
{
try
{
Hub.UnregisterAllAsync(oldDeviceToken, (error) =>
{
//check for errors in unregistration process.
if (error != null)
{
ApplicationLog.AppendFile(DateTime.Now.ToString() + " : " + "[PNS EXCEPTION] - Exception has been hit! - Message: " + error + " | Source: " + "Unregistering old device token against the notification hub.");
//exit out of the code here because we can't keep our hub clean without being able to remove the device from our registration list.
return;
}
else
{
ShouldComplete = true;
}
});
}
catch (Exception genEx)
{
ApplicationLog.AppendFile(DateTime.Now.ToString() + " : " + "[PNS EXCEPTION] - Exception has been hit! - Message: " + genEx.Message + " | Source: " + genEx + Environment.NewLine + Environment.NewLine);
}
}
}
else
{
// Store current device token
bool res = await ApplicationSettings.CacheDeviceToken(deviceToken);
}
// Check if we need to perform our initial registrations
if (ShouldComplete)
{
NSSet RegisteredTags = await ApplicationSettings.RetrieveUserTags();
if (RegisteredTags == null)
{
RegisteredTags = new NSSet("AppleDevice");
}
//Register the device against the notification hub keeping the details accurate at all times.
Hub.RegisterNativeAsync(deviceToken, RegisteredTags, (errorCallback) =>
{
if (errorCallback != null)
{
ApplicationLog.AppendFile(DateTime.Now.ToString() + " : " + "[PNS EXCEPTION] - Exception has been hit! - Message: " + errorCallback + " | Source: " + "Registering device token against the notification hub.");
}
else
{
if (deviceToken != null)
{
NSUserDefaults.StandardUserDefaults.SetString("Completed", "InitialTagRegistration");
NSUserDefaults.StandardUserDefaults.Synchronize();
}
}
});
}
}
The long and short of it is that you don't need to do anything to the device token before passing it up to the azure notification hub. That's what solved the problem for us, ours has been running in an active application for months now without any issues. Hope this helps.
EDIT: in order to update the tags when a user logs in, we store the device token for use later on, and when the user logs in we use the following method in a seperate class to facilitate updating the tags:
public static async Task<bool> UpdateTags(StaffProfile user)
{
//Get the instance of the Notification hub
SBNotificationHub UpdateHub = new SBNotificationHub(ConfigurableSettings.NotificationHubConnectionString, ConfigurableSettings.NotificationHubPathName);
//Grab the current device token that was stored during the start up process.
NSData CurrentDeviceToken = await ApplicationSettings.RetrieveDeviceToken();
//Get and create the tags we want to use.
string EmailTag = string.Empty;
string StoreTag = string.Empty;
string OrganisationTag = "AppleDevice:OrgTag";
string GenericTag = "AppleDevice:StaffTag";
if (!string.IsNullOrWhiteSpace(user.Email))
{
EmailTag = user.Email;
//Remove unwanted spaces and symbols.
EmailTag = EmailTag.Replace(" ", "");
EmailTag = string.Format("AppleDevice:{0}", EmailTag);
}
if (!string.IsNullOrWhiteSpace(user.Store?.Name))
{
StoreTag = user.Store.Name;
//Remove unwanted space.
StoreTag = StoreTag.Replace(" ", "");
StoreTag = string.Format("AppleDevice:{0}", StoreTag);
}
//Create array of strings to the currently fixed size of 3 items.
NSString[] TagArray = new NSString[4];
//Only add in the tags that contain data.
if (!string.IsNullOrEmpty(EmailTag)) { TagArray[0] = (NSString)EmailTag; }
if (!string.IsNullOrEmpty(StoreTag)) { TagArray[1] = (NSString)StoreTag; }
if (!string.IsNullOrEmpty(OrganisationTag)) { TagArray[2] = (NSString)OrganisationTag; }
if (!string.IsNullOrEmpty(GenericTag)) { TagArray[3] = (NSString)GenericTag; }
NSSet tags = new NSSet(TagArray);
// Store our tags into settings
ApplicationSettings.CacheUserTags(tags);
try
{
if (CurrentDeviceToken == null)
{
ApplicationLog.AppendFile(DateTime.Now.ToString() + " : " + "[PNS EXCEPTION] - Exception has been hit! - Message: Device token is empty." + Environment.NewLine + Environment.NewLine);
}
else
{
UpdateHub.RegisterNativeAsync(CurrentDeviceToken, tags, (error) =>
{
//check for errors in unregistration process.
if (error != null)
{
ApplicationLog.AppendFile(DateTime.Now.ToString() + " : " + "[PNS EXCEPTION] - Exception has been hit! - Message: " + error + " | Source: " + "Registering against hub with new tags." + Environment.NewLine + Environment.NewLine);
// Lets do this so that we can force the initial registration to take place again.
NSUserDefaults.StandardUserDefaults.SetString("Failed", "InitialTagRegistration");
NSUserDefaults.StandardUserDefaults.Synchronize();
}
else
{
ApplicationLog.AppendFile(DateTime.Now.ToString() + " : " + "[INFORMATION] - Message: Successful Registration - Source: Registering against hub with new tags." + Environment.NewLine + Environment.NewLine);
}
});
}
}
catch (Exception genEx)
{
ApplicationLog.AppendFile(DateTime.Now.ToString() + " : " + "[PNS EXCEPTION] - Exception has been hit! - Message: " + genEx.Message + " | Source: " + genEx + Environment.NewLine + Environment.NewLine);
}
return await Task.FromResult(true);
}
I have tried with fallowing code but i didn't receive any notification. At first time when i send test notification in azure notification hub it will shows one success but didn't receive notification, after second time onward it shows 0 passed and 0 failed.
According to your description, I would recommend you could communicate with APNs directly to check whether you could get the error response to narrow this issue. Here are some useful tutorials, you could refer to them and troubleshoot your issue as follows:
Official documentation:Communicating with APNs
Knuff, a debug application for Apple Push Notification Service (APNs)
PushSharp, a server-side library for sending notification to iOS/OSX (APNS), Android/Chrome (GCM), Windows/Windows Phone, Amazon (ADM) and Blackberry devices. For how to configure and send Apple Push Notifications, you could refer to here.