I am trying to make a very little application. My app will fetch an url:
example.com/response.json
when this response "true" my app will send a notification message:
Your thing is ready! Let's see.
But I have no idea how to make it? Do I need a Timer or what?
I found this method:
private static void generateNotification(Context context, String message) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "Message received", System.currentTimeMillis());
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
//adding LED lights to notification
notification.defaults |= Notification.DEFAULT_LIGHTS;
Intent intent = new Intent(context, MessageReceivedActivity.class);
intent.putExtra("payload", payload);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
notification.setLatestEventInfo(context, "Message", "New message received", pendingIntent);
notificationManager.notify(0, notification);
}
But how to check every 5min the response and send the notification?
download this file using i.e. HttpURLConnection or HttpClient inside AsyncTask doInBackground method. example of fetching data:
HttpGet reqest = new HttpGet(yourURL);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(reqest);
String result = EntityUtils.toString(response.getEntity());
for parsing JSON use JSONObject(String json) passing result (and/or optionally JSONArray if needed)
if result matches your expectations use Toast.makeText(...) or Notifications (example here)
Related
Months ago I wrote a code that my Notification worked as bellow :
NotificationManager NotiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
String MyText = "NotificationText";
Notification mNotification = new Notification(R.mipmap.icon, MyText, System.currentTimeMillis() );
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotification.defaults |= Notification.DEFAULT_SOUND;
mNotification.defaults |= Notification.DEFAULT_VIBRATE;
String MyNotificationTitle = "AnyText";
String MyNotificationText = "HERE MORE TEXT";
Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://www.google.com"));
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent StartIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
mNotification.setLatestEventInfo(context.getApplicationContext(), MyNotificationTitle, MyNotificationText, StartIntent);
NotiManager.notify(NOTIFY_ME_ID_LOGIN, mNotification);
But now, that I want to make an update it doesn't even let compile the APP because this line :
mNotification.setLatestEventInfo(context.getApplicationContext(), MyNotificationTitle, MyNotificationText, StartIntent);
Is there any way to change the setLatestEventInfo or other way to create a Notification?
Is there any way to change the setLatestEventInfo
You are welcome to lower your compileSdkVersion, though that will introduce its own set of issues.
or other way to create a Notification?
As Blackbelt notes in a comment, NotificationCompat.Builder has been around for ~4 years and is the recommended way to create Notification objects today:
private void raiseNotification(String mimeType, File output,
Exception e) {
NotificationCompat.Builder b=new NotificationCompat.Builder(this);
b.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL);
if (e == null) {
b.setContentTitle(getString(R.string.download_complete))
.setContentText(getString(R.string.fun))
.setSmallIcon(android.R.drawable.stat_sys_download_done)
.setTicker(getString(R.string.download_complete));
Intent outbound=new Intent(Intent.ACTION_VIEW);
outbound.setDataAndType(Uri.fromFile(output), mimeType);
b.setContentIntent(PendingIntent.getActivity(this, 0, outbound, 0));
}
else {
b.setContentTitle(getString(R.string.exception))
.setContentText(e.getMessage())
.setSmallIcon(android.R.drawable.stat_notify_error)
.setTicker(getString(R.string.exception));
}
NotificationManager mgr=
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
mgr.notify(NOTIFY_ID, b.build());
}
(from this sample project, which is in this directory of sample projects all showing how to display Notifications)
I am trying to set the correct URI for a custom sound in a phonegap app. I have tried several combinations including the following but I keep getting a Uri cannot be resolved
notif.sound = Uri.parse("android.resource://package_name/raw/notification/alarm.WAV");
notif.sound = Uri.parse("android.resource://package_name/raw/notification/");
notif.sound = Uri.parse("file://path/to/file/alarm.WAV");
How do I set the Uri for a sound when using phonegap
More info
I am using this tutorial at the end of which it explains how to add notifications from a push message....
String message = extras.getString("message");
String title = extras.getString("title");
Notification notif = new Notification(android.R.drawable.btn_star_big_on, message, System.currentTimeMillis() );
notif.flags = Notification.FLAG_AUTO_CANCEL;
notif.defaults |= Notification.DEFAULT_SOUND;
notif.defaults |= Notification.DEFAULT_VIBRATE;
Intent notificationIntent = new Intent(context, TestSampleApp.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notif.setLatestEventInfo(context, title, message, contentIntent);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager)
context.getSystemService(ns);
mNotificationManager.notify(1, notif);
I thought removing Notification.DEFAULT_SOUND; and adding the uri would make it place a custom sound.
If that's JavaScript code, the problem is with the code and how you defined the Uri variable/library.
If you are using the notification API, there's no way to specify the default "beep" sound (except for iOS, but that's because there isn't a beep sound on iOS.)
If you are trying to play a specific sound, I think you should be using the media API. You can specify a sound to play like this:
function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
// success callback
function() {
console.log("playAudio():Audio Success");
},
// error callback
function(err) {
console.log("playAudio():Audio Error: "+err);
});
// Play audio
my_media.play();
}
Take a look at the "full example" to see how to set up the HTML page correctly.
I'm building an android app which supports push notifications using phonegap/cordova and this plugin. The plugin has an onMessage() method which is triggered whenever a push notification is received, this method returns a json object to my javascript plugin. However I want this method to return the json only when the notification on status bar is clicked.
This is my onMessage() method:
protected void onMessage(Context context, Intent intent) {
String message = "", title = "", type = "";
int msgctn = 0, schoolid = 0, studentid = 0, contentid = 0;
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null) {
try
{
message = extras.getString("message");
title = extras.getString("title");
type = extras.getString("type");
msgctn = Integer.parseInt(extras.getString("msgctn"));
schoolid = Integer.parseInt(extras.getString("schoolid"));
studentid = Integer.parseInt(extras.getString("studentid"));
contentid = Integer.parseInt(extras.getString("contentid"));
JSONObject json;
json = new JSONObject().put("event", "message");
json.put("message", message);
json.put("type", type);
json.put("contentid", contentid);
json.put("schoolid", schoolid);
json.put("studentid", studentid);
GCMPlugin.sendJavascript( json );
// Send the MESSAGE to the Javascript application
}
catch( JSONException e)
{
Log.e(ME + ":onMessage", "JSON exception");
}
Intent notificationIntent = new Intent(context, App4.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentText(message)
.setContentTitle(title)
.setSmallIcon(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? R.drawable.icon : android.R.drawable.ic_dialog_info)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setWhen(System.currentTimeMillis())
//.setDefaults(Notification.DEFAULT_ALL)
.setLights(-16711681, 2000, 1000)
.setNumber(msgctn)
.setSound(Uri.parse("android.resource://"+ getPackageName() + "/" + R.raw.notifsound));
Notification notification = builder.build();
NotificationManager notificationManager = getNotificationManager(context);
notificationManager.notify(1, notification);
}
I had to create a notification object in order to show it on status bar. When the notification is clicked it calls intent App4, this shows the index.html of my app, but I want to execute some javascript function or return some json object to my app using the payload. Maybe I can call other function to do this, not an intent but I'm new on android world and don't know how to do it.
Can anyone help me please?
What you can do is put the JSON data as extras in the notificationIntent Intent that you are creating. You can do this by calling the putExtras() method of your notificationIntent, or do it manually. Whichever way you do it you need to get the data you want into the notificationIntent as extras.
Then when your App4 activity starts you will need catch the Intent in either onNewIntent() or onCreate() and check to see if the Intent or Bundle has the extras that you want. If it does then you create the JSON object and pass it to your javascript application just like you did in the onMessage() method you pasted.
You will also have to remove the code that sends the JSON object to your javascript application in the onMessage() method.
I hope that helps, it should work but I'm away from my computer and can't actually test the code.
Is it possible to send an audio file as a push notification in android ? What i want to do is that the user can record his voice as a message and then that message should be delivered to all the users with that app as a push notification . is it possible ?
According to below document, CGM / C2DM / Push Notification can send only 4KB data, So, you can not send audio files via push notification,
http://developer.android.com/guide/google/gcm/c2dm.html
"Apps can use "messages with payload" to deliver messages of up to 4 Kb"
But you can send http url of any audio file, in mobile app will receive audio file link via cgm message and download audio file using http connection.
The other way to do it, is use a module that has already implemented this for you. Technically you do the exact same thing that is described here, however with a single API call to providers like mBlox (http://developer.mblox.com), you'll be able to post your content and the devices you want to target, the hosting of the content, and the translation to a URL are being done for you, as well as sending the actual push notification.
Again, technically, it's the same as previous answers, however, for your personal integration it might be a quicker way to get to market.
There is a Way, we can send a audio url in data from FCM. After that we can parse and sent to another activity.
In FIREBASE SERVICE
JSONObject object = null;
try {
String data = remoteMessage.getData().toString();
Map<String, String> params = remoteMessage.getData();
object = new JSONObject(params);
} catch (Exception e) {
Log.e("FCM err 1", e.getMessage());
}
sendNotification(this, remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getClickAction(), object);
PUSH NOTIFICATION FUNCTION
public static void sendNotification(Context context, String Message, String Title, String ClickAction, JSONObject object) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
final String CHANNEL_ID = "KRB";
if (Build.VERSION.SDK_INT >= 26) { // Build.VERSION_CODES.O
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, "KRB_channel", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
}
// intent = Home
Intent intent = new Intent(ClickAction);
try {
Log.e("FCMurl", object.getString("url"));
Log.e("FCMtype", object.getString("type"));
intent.putExtra("url", object.getString("url"));
intent.putExtra("type", object.getString("type"));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
} catch (Exception e) {
// Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("FCM err", e.getMessage());
}
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.icon_logo)
.setColor(Color.parseColor("#531E6C")) // small icon background color
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_sfach))
.setContentTitle(Title)
.setContentText(Message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL)
.setContentIntent(pendingIntent);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
In activity
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String url;
if(bundle != null){
url = bundle.getString("url");
MediaPlayer mediaplayer = new MediaPlayer();
try {
mediaplayer.setDataSource(url);
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaplayer.prepareAsync();
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaplayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
I am using following code to get notifications from a service
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this,test.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent,Notification.FLAG_AUTO_CANCEL);
String body = "Hi this is test"+count;
String title = "Ritu"+count;
Notification n = new Notification(R.drawable.icon,body,System.currentTimeMillis());
n.setLatestEventInfo(this, title, body, pi);
n.defaults = Notification.DEFAULT_LIGHTS;
n.number=++count;
nm.notify(uniqueid, n);
Every time I am getting a new notification, the number on it gets incremented but when I open notification window I can see only one the latest notification and after clicking on it number of notification does not get decremented.
Where I am wrong please help.
Thanks!
Try this, in order to remove notification after click:
n.flags |= Notification.FLAG_AUTO_CANCEL;
And instead of using:
n.number = ++count;
Use:
count++;
nm.notify(count, n);
This will allow you to have multiple notifications at the same time
Follow this like if u can get help...
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/NotifyWithText.html