Android Notification into Alert Notification - java

I built an notification which works so far.
Since I did not know that it works only inside of my application I read through some articles and saw that I need an 'Alarm Notification'.
I tried varous things but none did not work, now I am asking here.
My Notification in my Mainactivity looks like this:
public static final int NOTIFICATION_ID_01 = 1;
public void sendNotificationIfTimeEnd01() {
Context context = getApplicationContext();
Intent intent01 = new Intent(context, MainActivity.class);
PendingIntent pendingIntent01 = PendingIntent.getActivity(this, 1, intent01, 0);
NotificationCompat.Builder builder01 = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pendingIntent01)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setContentTitle(gamesJuliToStringArray[0])
.setContentText("Ready")
.setSubText("click");
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID_01, builder01.build());
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
I am accesing this notification in my Fragment if a specific conditions happens:
final MainActivity activity = (MainActivity) getActivity();
if (i = 10) {
activity.sendNotificationIfTimeEnd01();
editor.putBoolean("notification01", true);
editor.apply();
}
Again I want to transform this Notification into an 'Alarm' / 'Alarm Notification'.
I appreciate any response!

Related

How to open an activity on the lock screen after FCM notification

How can I open an activity on the lock screen without the user having to click on it? Like for example an alarm or a call.
In my code I can get the FCM notification and if the user clicks on the notification it is possible to open an activity, but I wanted the user not to have to click on it.
FirebaseService.java
//--- Notificacao
public void createNotificationChannel(){
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
//create a notification channel
NotificationChannel notificationChannel = new NotificationChannel(PRIMARY_CHANNEL_ID,
"Mascot Notification", NotificationManager
.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Notification from Mascot");
mNotifyManager.createNotificationChannel(notificationChannel);
}
}
public void sendNotification(String taskName){
NotificationCompat.Builder notifyBuilder = getNotificationBuilder(taskName);
//agora temos que entregar a notificacao
mNotifyManager.notify(NOTIFICATION_ID, notifyBuilder.build());
}
public NotificationCompat.Builder getNotificationBuilder(String taskName){
Intent intent = new Intent(this, TesteActivity.class);
PendingIntent p = getPendingIntent(NOTIFICATION_ID, intent, getApplicationContext());
return new NotificationCompat.Builder(this, PRIMARY_CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentText("titulo teste")
.setContentIntent(p)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
}
private PendingIntent getPendingIntent(int id, Intent intent, Context context){
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(intent.getComponent());
stackBuilder.addNextIntent(intent);
PendingIntent p = stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
return p;
}
TesteActivity.java
public class TesteActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teste);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setTurnScreenOn(true);
setShowWhenLocked(true);
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
keyguardManager.requestDismissKeyguard(this, null);
}
instead of mNotifyManager.notify( call, which shows your Notification, just use startActivity(..? you may need also WakeLock and showOnLockScreen attribute set for this Activity in manifest
edit: and HERE you can find article with exactly your case tutorial

Using startForeground with android service

I have found this Question : How to use startForeground? in Stackoverflow and as it says in the command from the top answer the notification constructor and setLastEventInfo is deprecated. I know that's a duplicated post but the other post is 4 years old and has no answer in the commends so I thought i try do ask it again maybe someone can help me with this.
Code:
Notification note = new Notification(R.drawable.ic_launcher,
"Foreground Service notification?", System.currentTimeMillis());
Intent i = new Intent(this, CurrentActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
Date dateService=new Date(System.currentTimeMillis());
String dateString=dateService.toString().split(" ")[1]+" "+dateService.toString().split(" ")[2]+" "+dateService.toString().split(" ")[3];
note.setLatestEventInfo(this, "Foreground service",
"Now foreground service running: "+dateString, pi);
note.flags |= Notification.FLAG_AUTO_CANCEL;
startForeground(2337, note);
You can use this method. Now with latest API versions you need to set channel for notifications.
private static final String NOTIFICATION_CHANNEL_ID ="notification_channel_id";
private static final String NOTIFICATION_Service_CHANNEL_ID = "service_channel";
.....
private void startInForeground() {
int icon = R.mipmap.icon;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
icon = R.mipmap.icon_transparent;
}
Intent notificationIntent = new Intent(this, CurrentActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(icon)
.setContentIntent(pendingIntent)
.setContentTitle("Service")
.setContentText("Running...");
Notification notification=builder.build();
if(Build.VERSION.SDK_INT>=26) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_Service_CHANNEL_ID, "Sync Service", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Service Name");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
notification = new Notification.Builder(this,NOTIFICATION_Service_CHANNEL_ID)
.setContentTitle("Service")
.setContentText("Running...")
.setSmallIcon(icon)
.setContentIntent(pendingIntent)
.build();
}
startForeground(121, notification);
}

Android Java Notification To Alarm

How do I rebuilt my Notification to get a 'Notification Alarm'
I tried varois things but nothing worked, I am really frustated so I finally ask here.
Main Activity:
public void sendNotificationIfTimeEnd01() {
Context context = getApplicationContext();
Intent intent01 = new Intent(context, MainActivity.class);
PendingIntent pendingIntent01 = PendingIntent.getActivity(this, 1, intent01, 0);
NotificationCompat.Builder builder01 = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pendingIntent01)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setContentTitle(gamesJuliToStringArray[1])
.setContentText("Spiel ist bereit")
.setSubText("click");
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID_01, builder01.build());
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
Condition in my Fragment:
if (!notification062 && !buttonColor02.equals("red02")) {
activity.sendNotificationIfTimeEnd01();
}
Again I get Notifications if the conditions happens, but only inside of my application.
Need help for rebuilding this into and alarm notification
Here you can see an example of the AlarmManager being used to schedule a notification for a later time, given a specific delay.

Android java sent notification once

How do I sent the notification only once if something happens?
I got this statement:
if (diffDays <= 0 && diffHours <= 0 && diffMinutes <= 0) {
activity.sendNotificationIfTimeEnd01();
Log.d("MyApp", "I am here");
}
and this:
public void sendNotificationIfTimeEnd01() {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.google.de/?gws_rd=ssl"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.ic_stat_notification);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
builder.setContentTitle("String one");
builder.setContentText("bla");
builder.setSubText("blabla");
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
I do get the notification if the statement is right, but if I close the app and start it I get the notification again.(Statement is still right);
Try using SharedPreferences as bleeding182 adviced you. This is a good answer on how to do that:
How to use SharedPreferences in Android to store, fetch and edit values

How to check which notification id is clicked?

My application is receiving GCM notifications. I have different type of notifications and at some point the user can have more than one notification in the status bar. However I need to know which one exactly he clicked on. In the GCM onMessage Im setting them with
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(Integer.parseInt(notification_id), notification);
I need to get that notification_id after the click on the notification. I am pretty sure that's something simple but I couldnt find any info about it.
Here are the onMessage from GCMIntentService
#Override
protected void onMessage(Context context, Intent data) {
String content_title;
String content_text;
String event_id;
String content_info;
String url;
String match_id;
// Message from PHP server
content_title = data.getStringExtra("content_title");
content_text = data.getStringExtra("content_text");
content_info = data.getStringExtra("content_info") + "'";
event_id = data.getStringExtra("event_id");
match_id = data.getStringExtra("match_id");
url = data.getStringExtra("url");
NOTIFICATION_URL = url;
// Open a new activity called GCMMessageView
Intent intent = new Intent(this, GCMMessageView.class);
// Pass data to the new activity
intent.putExtra("message", content_title);
intent.putExtra("url", url);
// Starts the activity on notification click
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Options opts = new Options();
opts.inDither = true;
opts.inScaled = false;
/* Flag for no scalling */
// Create the notification with a notification builder
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(drawable_small).setLargeIcon(drawable_big)
.setWhen(System.currentTimeMillis()).setTicker(content_title)
.setContentTitle(content_title).setContentInfo(content_info)
.setContentText(content_text).setContentIntent(pIntent)
.getNotification();
// Remove the notification on click
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(Integer.parseInt(match_id), notification);
try {
Uri notification2 = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
notification2);
r.play();
} catch (Exception e) {
}
{
// Wake Android Device when notification received
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock mWakelock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
mWakelock.acquire();
// Timer before putting Android Device to sleep mode.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
mWakelock.release();
}
};
timer.schedule(task, 5000);
}
}
And there`s the on click
String msg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent.hasExtra("url"))
msg = intent.getExtras().getString("url");
Log.e("URL", msg);
setContentView(R.layout.activity_main);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(msg
+ "?device_id="
+ GCMIntentService.DEVICE_REGISTRATION_ID.toString()));
startActivity(browserIntent);
// Toast.makeText(getApplicationContext(),
// GCMIntentService.DEVICE_REGISTRATION_ID, Toast.LENGTH_LONG).show();
}
You can go through the below code, You have to ser Notification object as per your need.
String appname = context.getResources().getString(R.string.app_name);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Notification notification;
Intent intent = new Intent(context, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("message", YOUR_DATA);
int requestID = (int) System.currentTimeMillis();
PendingIntent contentIntent = PendingIntent.getActivity(context, requestID,
intent, 0);
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification(icon, message, when);
notification.setLatestEventInfo(context, appname, message,
contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify((int) when, notification);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(appname).setWhen(when)
.setAutoCancel(true).setContentTitle(appname)
.setContentText(message).build();
notificationManager.notify((int) when, notification);
}
When user click on any notification, it will re-direct to NotificationActivity class.
In this activity, in OnCreate() method you can get your data that is set.
Intent intent = getIntent();
if (intent.hasExtra("message"))
String msg = intent.getExtras().getString("message");
I think it will help.

Categories