Android open Chrome with notification - android

I'm developing an android app. It receive with a push notification an URL. I need to open the url with chrome. I'm trying with this but is not working
Intent i;
try {
i = new Intent(Intent.ACTION_VIEW);
i.setType("text/html");
i.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
i.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main"));
i.addCategory("android.intent.category.LAUNCHER");
i.setData(Uri.parse(audioLink));
} catch (ActivityNotFoundException ex) {
i = new Intent(Intent.ACTION_VIEW, Uri.parse(audioLink));
}
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder;
NotificationManager manager;
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.newmessagetitle))
.setContentText(getString(R.string.newmessage))
.setSmallIcon(R.mipmap.ic_stat_lollipop_icon);
builder.setContentIntent(pendingIntent);
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
defaults = defaults | Notification.DEFAULT_VIBRATE;
defaults = defaults | Notification.DEFAULT_SOUND;
builder.setDefaults(defaults);
builder.setAutoCancel(true);
manager.notify(notifyID, builder.build());

I really think something like this should work for the intent code. If not, there is probably something wrong with another part of your code:
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(audioLink));
i.setPackage("com.android.chrome");
By the way the ActivityNotFoundException is totally useless in that place, because only Activity.startActivity() throws that exception. If you want to check if Chrome is installed, I would use this: How can I learn whether a particular package exists on my Android device?

Related

How to open Play Store via a FCM notification?

I would like to send a notification to my users to remember them to update the app, but I can't change the app code as obviously the problem is that the app is outdated.
Is there a way to open Play Store via a FCM notification, using clickAction or something like that, without needing to make changes to the app?
you can open play store-specific app using FCM you just need to put following logic in your onMessageReceived of your FCM custom class.
Bellow is the Logic:
public static void openStore(Context context,RemoteMessage remoteMessage) {
Intent intent;
if (remoteMessage.getData().containsKey("appPackageName")) {
final String appPackageName = remoteMessage.getData().get("appPackageName"); // getPackageName()
try {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName));
} catch (android.content.ActivityNotFoundException anfe) {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName));
}
int notificaionId = 1;
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.BigTextStyle bigTextNotiStyle = null;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int color = ContextCompat.getColor(this, R.color.profileFontColor);
NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_notification)
.setContentTitle("" + remoteMessage.getData().get("title"))
.setContentText("" + remoteMessage.getData().get("desc"))
.setStyle(bigTextNotiStyle)
.setAutoCancel(true)
.setColor(color)
.setContentIntent(pIntent)
.setLights(Color.RED, 3000, 3000);
notificationManager.notify(notificaionId, mBuilder.build());
}
}

NotificationCompat setSound(sound, STREAM_ALARM) not working

Im building a ping feature for finding a lost phone through bluetooth. I need the phone to sound even though it is set to mute/silent like how the alarm usually works. I thought I could put the streamtype of my notification to AudioManager.STREAM_ALARM but its not working. It only sounds when the phones sound is on. This is how I set it:
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
builder.setSmallIcon(R.drawable.ic_spenwallet)
.setContentTitle("Ping")
.setContentText("Device is trying to find your phone.")
.setAutoCancel(false)
.setSound(sound, STREAM_ALARM)
.setVibrate(vibratePattern)
.addAction(cancelAction);
If I try :
Notification notification = builder.build();
notification.audioStreamType = AudioManager.STREAM_ALARM;
Im getting a warning from Android Studio that audioStreamType is deprecated. Is this the case? Any other way to make the notificaiton sound even though silent mode is on? (preferable also vibrate)
I got it working by creating a dedicated mediaplayer for the purpose but I don't think this should be needed. Heres how I did it anyway:
MediaPlayer mediaPlayer = new MediaPlayer();
final String packageName = getApplicationContext().getPackageName();
Uri sound = Uri.parse("android.resource://" + packageName + "/" + R.raw.ping_sound);
try {
mediaPlayer.setDataSource(this, sound);
} catch (IOException e) {
e.printStackTrace();
}
final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setLooping(false);
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
Using builder.setSound(alarmSound, AudioManager.STREAM_AUDIO) was exactly what I needed to keep my alarm going! Perhaps your issue is with the R.raw.ping_sound sound sample that you are using. After trying a bunch of terrible implementations I found online for alarm notifications (which is where I found Settings.System.DEFAULT_RINGTONE_URI) I followed the official notification documentation and then used the NotificationCompat.Builder documentation for customization.
Here is my working alarm notification:
private void showNotification(){
// Setup Intent for when Notification clicked
Intent intent = new Intent(mContext, MedsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // See https://developer.android.com/training/notify-user/navigation for better navigation
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
// Setup Ringtone & Vibrate
Uri alarmSound = Settings.System.DEFAULT_RINGTONE_URI;
long[] vibratePattern = { 0, 100, 200, 300 };
// Setup Notification
String channelID = mContext.getResources().getString(R.string.channel_id_alarms);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext, channelID)
.setContentText(notificationMessage)
.setContentTitle(notificationTitle)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(pendingIntent)
.setSound(alarmSound, AudioManager.STREAM_ALARM)
.setOnlyAlertOnce(true)
.setVibrate(vibratePattern)
.setAutoCancel(true);
// Send Notification
NotificationManager manager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, mBuilder.build());
}

Notification - cannot resolve symbol setLastEvenInfo

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)

How to correctly open file on notification click

I'm donloading files from the Internet using IntentService and displaying a Notification while download is in progress. After download complete I need to be able to click on the notification to open downloaded file in appropriate application. Here's a code I'm using for this:
Intent intent = IntentUtils.getOpenFileIntent(task.getTargetFolder()
+ File.separator + task.getFileNode().getName());
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(this);
taskStackBuilder.addParentStack(MainActivity.class);
taskStackBuilder.addNextIntent(intent);
PendingIntent pi = taskStackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi);
And here's how I create the Intent:
public static Intent getOpenFileIntent(String path) {
File file = new File(path);
Uri uri = Uri.fromFile(file);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String extension = fileExt(path);
String type = mime.getMimeTypeFromExtension(extension);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, type);
return intent;
}
The issue is that tapping on the notification closes any of the currently opened app. I just need to display application chooser over the currently opened app. I think that the issue is in TaskStackBuilder usage but there's no other way to create PendingIntent instance for ACTION_VIEW Intent.
You need to create PendingIntent and set to your Notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_CANCEL_CURRENT)
Fore more information go to http://developer.android.com/guide/topics/ui/notifiers/notifications.html
private NotificationManager manager;
private Intent notiIntent;
/// id is integre value which in unique for notifications
notiIntent= new Intent(context, CurrentActiivty.class);
notiIntent.putExtra("id", id);
notiIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
Notification notification = new Notification(R.drawable.icon, "your text on notification bar", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notiIntent, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(context,"text here", message, contentIntent);
notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
notiIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
manager.notify(id, notification);
Now In calling actiivty write the following code
Bundle extras = getIntent().getExtras();
int id= extras.getInt("id");
NotificationManager notificationManager;
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(id);

how to add route icon in notification android

private void showNotification() {
NotificationManager mNotificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
Notification notifyDetails = new Notification(R.drawable.alert_light_frame,"Alarma!",System.currentTimeMillis());
PendingIntent myIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(Intent.ACTION_VIEW, People.CONTENT_URI), 0);
notifyDetails.setLatestEventInfo(getApplicationContext(), "Alarma!", nombre, myIntent);
notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
notifyDetails.icon |= HEREEEEEEEEEEE
mNotificationManager.notify(SIMPLE_NOTFICATION_ID++, notifyDetails);
Log.i(getClass().getSimpleName(),"Sucessfully Changed Time");
}
in "HEReeeeeeeeeeeee" i need put a route, for example "/mnt/sdcard/Pou/4_1362782019815.png"
Thx.
Try using Notification.Builder to build up your notifications as it makes things more convenient and additionally has a setLargeIcon() method that you can use to pass in any Bitmap you want (including one you load from the sdcard). There's also NotificationCompat.Builder in the support library if you need to target pre-Honeycomb
1) Get icon bitmap from sdcard:
File f = new File("/mnt/sdcard/photo.jpg");
Bitmap notificationIconBmp = BitmapFactory.decodeFile(f.getAbsolutePath());
2) Set bitmap for notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setLargeIcon(notificationIconBmp);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify("direct_tag", NOTIF_ALERTA_ID, builder.build());

Categories

Resources