Non activity class notification not working - java

I'm trying to make a notification appear in the notification manager from a non activity class, but I can't make it happen
public void showNotification(Context context) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
//.setSmallIcon(R.drawable.notif1)
.setContentTitle("Car crash occure!")
.setContentText("Tap to view location.");
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MapsActivity.class), 0);
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}

Use Intent Service instead of Activity
public static class NotificationActionService extends IntentService {
public NotificationActionService() {
super(NotificationActionService.class.getSimpleName());
}
#Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (ACTION_1.equals(action)) {
Log.d("ACTION_NOTIFICATION", "Notification Clicked");
}
// TODO: handle action 1.
// If you want to cancel the notification: NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID);
}
}

Related

How to Return to activity after the notification has appeared? Notification is not clickable

I have problem - it is not possible to return to the main activity after clicking on the received notification. The notification itself is not clickable. The notification is triggered in the onPause method (in the background)
My main activity is MainActivity, which is setting up notification via PendingIntent and AlarmManager
public class MainActivity extends AppCompatActivity {
private NotificationManager notificationManager;
private static final int NOTIFY_ID = 1;
private static final String CHANNEL_ID = "CHANNEL_ID";
NotificationPublisher notificationPublisher;
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
CharSequence name = "LemubitReminderChannel";
String description = "Channel for Lemubit Reminder";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("notifyLemubid", name, importance);
channel.setDescription(description);
notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
}
private void reminderMethod (){
Toast.makeText(this, "Напоминание о запуске фонового уведомления", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), NotificationPublisher.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
long inPauseTime = System.currentTimeMillis();
long ten = 2 * 1000;
alarmManager.set(AlarmManager.RTC_WAKEUP, inPauseTime + ten, pendingIntent);
}
#Override
protected void onPause() {
super.onPause();
reminderMethod();
}
}
Broadcast receiver
public class NotificationPublisher extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
int unicode = 0x1F62D;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "notifyLemubid")
.setAutoCancel(true)
.setContentTitle("текст " + getEmojiByUnicode(unicode))
.setContentText("текст")
.setSmallIcon(R.drawable.ic_launcher_background)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
notificationManagerCompat.notify(200, builder.build());
}
public String getEmojiByUnicode(int unicode){
return new String(Character.toChars(unicode));
}
}
You need to set the contentIntent on the Notification, then, when the user clicks the Notification, the contentIntent will be dispatched. If you want the user to open an Activity of your app, then just create an Intent to your Activity, wrap that in a PendingIntent and call setContentIntent() on the `Notification. There's hundreds of howtos and tutorials for how to do this, just search a bit.

How to trigger a launch Activity intent when my app is closed on Android 10/Q?

I am trying to create an app that will open another app at a specified time. To do this, I used an AlarmManager that starts a service. It works just fine if my app is open when the alarm is triggered. I get a notification that the service started, and the other app opens. However, if my app is in the background (after pressing the home button), and the alarm triggers, I get a notification that the service started, but the other app does not launch. What am I doing wrong? I am testing this on a Pixel 3 emulator running API level 29 (Android 10/Q).
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CODE=101;
public static int aHour;
public static int aMinute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void setAlarm() {
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, amReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, aHour);
calendar.set(Calendar.MINUTE, aMinute);
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
//Some code that sets aHour and aMinute
//Some code that triggers setAlarm()
}
amReciever.java
public class amReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, launcherService.class);
ContextCompat.startForegroundService(getApplicationContext(), i);
}
}
launcherService.java
public class launcherService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText("App is launching.")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
Intent launcher = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.example.app");
if (launcher != null) {
startActivity(launcher);
}
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<service android:name=".launcherService"
android:enabled="true"
android:exported="true" />
As of Android 10 (API level 29), you cannot start activities from the background anymore.
There are a number of exceptions to this rule that may or may not apply to your given scenario.
If none of the exceptions apply, you might want to consider displaying a high-priority notification, possibly with a full-screen Intent.

Android notification dont open activity?

I have an app that sends/receives notification using Firebase. Im sending the notification with no problem, but if the app is open the notification display an square instead of the smallicon also if i click the notification nothing happens, but if i'm using a different app i receive the notification and the notification show the correct icon and also opens the app.
public class MyMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
public void showNotification(String title, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "MyNotifitcation")
.setContentTitle(title)
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true)
.setContentText(message);
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(999, builder.build());
}
}
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel =
new NotificationChannel("MyNotifitcation", "MyNotifitcation", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
FirebaseMessaging.getInstance().subscribeToTopic("general").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
String msg = "Successfull";
if (!task.isSuccessful()) {
msg = "Failed";
}
// Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
}
For Notification click add Pending intent to notification builder. and for adding image/icon to notification use setSmallIcon() in notification builder. below is my notification code.
private void sendNotification(String body, String title) {
Intent intent = new Intent(this, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("action_type", "notify");
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this,"channel")
.setSmallIcon(R.drawable.logo)
// .setContent(contentView)
.setContentTitle("title")
.setContentText("body")
.setAutoCancel(true)
.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
See below code. Opening Activity.
original post credit
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
Intent notificationIntent = new Intent(context, HomeActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);

Why is my Android notification not showing?

So, I'm developing an Android App and I need to send a notification of a certain event at a certain time.
However, for some reason the notification itself isn't showing up, despite the app not returning any errors or anything of the sort.
What could I possibly be doing wrong? This is my Receiver class.
The test print works properly so I don't think the connection to the receiver is the problem.
public class NotReceiver extends BroadcastReceiver{
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("test");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle("doge")
.setContentText("456")
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
}
This is my Alarm function
#RequiresApi(api = Build.VERSION_CODES.O)
public void sendNotif(View view) {
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent;
PendingIntent pendingIntent;
myIntent = new Intent(EventsActivity.this, NotReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);
am.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+100, pendingIntent);
}

Repeating notification sound

Is it possible (and if yes how) to make push notification sound repeat until it's read? I am creating app that notifies user about new event in app, but user needs to read notification as soon as possible. When user "reads" notification it should stop ringing. Here's code:
public class GCMIntentService extends IntentService {
String mes;
HelperGlobals glob;
public GCMIntentService() {
super("GcmIntentService");
}
#SuppressLint("SimpleDateFormat")
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
glob = (HelperGlobals) getApplicationContext();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
// .... Doing work here
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
public void createPush(String title, String msg, Intent intent) {
Uri soundUri = Uri.parse("android.resource://example.project.com/" + R.raw.notification);
Context context = getApplicationContext();
Intent notificationIntent = new Intent(context, DoNothing.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification n = new Notification.Builder(this)
.setContentTitle(title)
.setContentText(msg)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true).build();
n.defaults |= Notification.DEFAULT_VIBRATE;
//n.defaults |= Notification.DEFAULT_SOUND;
n.sound = soundUri;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
}
}
And BroadcastReceiver:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BukuLog", "Receiver");
// Explicitly specify that GcmMessageHandler will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GCMIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
like this:
Notification note = mBuilder.build();
//here
note.flags = Notification.FLAG_INSISTENT;
mNotificationManager.notify(1, note);
int FLAG_INSISTENT : Bit to be bitwise-ored into the flags field that if set, the audio will be repeated until the notification is cancelled or the notification window is opened.
follow android developer

Categories

Resources