Notification Error FLAG_ACTIVITY_NEW_TASK - java

I am currently recieving an eror i have not experienced before. I want a basic notification to show when AlarmReciever.java is executed. The error is for FLAG_ACTIVITY_NEW_TASK.
Can anyone help with a solution?
Thank you!
AlarmReceiver:
package servicealarmdemo.test2;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
private static final int MY_NOTIFICATION_ID=1;
NotificationManager notificationManager;
Notification myNotification;
private final String myBlog = "http://android-er.blogspot.com/";
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, myIntent,Intent.FLAG_ACTIVITY_NEW_TASK);
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Exercise of Notification!")
.setContentText("http://android-er.blogspot.com/")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.build();
notificationManager =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}
}

public static PendingIntent getActivity (Context context, int requestCode, Intent intent, int flags){
...
}
The last parameter May be FLAG_ONE_SHOT, FLAG_NO_CREATE, FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT, or any of the flags as supported byIntent.fillIn() to control which unspecified parts of the intent that can be supplied when the actual send happens.
So your code could be like this:
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, myIntent,PendingIntent.FLAG_ONE_SHOT);

Related

Android Java Notification is not showing when app is closed

I set the alarm for the next day, when the time comes nothing happens. The notification is not being shown, but if I open the application; the notification show up. What can I do? Here is my code.
The documentation: https://developer.android.com/develop/ui/views/notifications/build-notification#java
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.core.app.NotificationCompat;
public class AlarmReceiver extends BroadcastReceiver {
private static final String CHANNEL_ID = "SAMPLE_CHANNEL";
#Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("notificationId",0);
String message = intent.getStringExtra("todo");
Intent mainIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,0,mainIntent,0);
NotificationManager myNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
CharSequence channel_name = "My Notification";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channel_name, importance);
myNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);
builder.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle("It's Time!")
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL);
myNotificationManager.notify(notificationId, builder.build());
}
}

Add Button to Notification

I need a button in my Notification, however everything i find online is not working. I need it to cancel playing an alarm that will go off at a designated time. Can anyone link me some articles to read or tell me what code i should use in order to get this to work.
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.RingtoneManager;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import com.example.oceansscheduler.MainActivity;
import com.example.oceansscheduler.R;
public class AlarmReceiver extends BroadcastReceiver {
public void showNotification(Context context, String title, String message, Intent intent, int reqCode) {
PendingIntent pendingIntent = PendingIntent.getActivity(context, reqCode, intent, PendingIntent.FLAG_ONE_SHOT);
String CHANNEL_ID = "channel_name";// The id of the channel.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_alarm_24)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle())
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentText(message)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Channel Name";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(reqCode, notificationBuilder.build()); // 0 is the request code, it should be unique id
Log.d("showNotification", "showNotification: " + reqCode);
}
#Override
public void onReceive(Context context, Intent intent) {
SQLiteDatabase db = context.openOrCreateDatabase("NotificationDatabase", android.content.Context.MODE_PRIVATE, null);
Cursor data = db.rawQuery("SELECT * FROM PersonalNotif", null);
Log.d("Count", String.valueOf(data.getCount()));
if (data.getCount() > 0) {
data.moveToFirst();
String NameOfNotif = (data.getString(0));
Toast.makeText(context, NameOfNotif, Toast.LENGTH_LONG).show();
int reqCode = 1;
Intent intentNotif = new Intent(context, MainActivity.class);
showNotification(context, NameOfNotif, "Your Reminder is going off!", intentNotif, reqCode);
}
}
};
To add a button in Your notification, You need to use addAction function.
It requires an Action object which needs:
an icon (oddly),
a title,
a PendingIntent
The PendingItent can encapuslate an Intent that can be a Service that will be delegated to cancel playing the alarm or a Receiver that will do it.
Let's stick with a receiver. We can create one - CancelAlarmReceiver:
public class CancelAlarmReceiver extends BroadcastReceiver {
public static String ACTION_CANCEL = "actionCancelAlarm";
public CancelAlarmReceiver() {}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_CANCEL)) {
// Here You will cancel the alarm.
}
}
}
Remember to register it in the Manifest:
<receiver
android:name=".CancelAlarmReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.your.app.CancelAlarmReceiver.ACTION_CANCEL" />
</intent-filter>
</receiver>
Later on, when creating a notification with a builder, You will have to provide an action leading to our Receiver:
Intent cancelIntent = new Intent(this, CancelAlarmReceiver.class);
cancelIntent.setAction(ACTION_CANCEL);
PendingIntent cancelPendingIntent =
PendingIntent.getBroadcast(this, NOTIFICATION_ID,
cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(
new Notification.Action(
R.drawable.ic_alarm_cancel,
getString(R.string.cancel_alarm),
cancelPendingIntent
)
);
This should make sure that a button will appear by Your notification and it will trigger the receiver and disable the alarm (or whatever You will make it to do).

How to send a notification at the exact time when the application is closed?

I am new to android studio. I need to create a note application with a reminder function. I decided to do this through the alarmmanager, but it only works when the application is open. Is it realistic to do this only through services?
I noticed that in the google keep application, when creating a reminder, a new service is created. How to do this?
Part of the code from the activity:
public void alarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
intent.putExtra("title",editTask.getText().toString());
PendingIntent pen = PendingIntent.getBroadcast(this, 1, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),pen);
AlertReciver.java
package denchic45.myapp.appmy;
import android.content.BroadcastReceiver;
import android.content.Intent; import android.widget.Toast;
import android.content.Context;
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
intent = new Intent(context, Services.class);
context.startService(intent);
Toast.makeText(context, "alarm", Toast.LENGTH_SHORT).show();
} }
Services.java
package denchic45.myapp.appmy;
import android.app.IntentService;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class Services extends IntentService {
public Services() {
super("public services");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Context context = getApplicationContext();
Toast.makeText(context, "WORK", Toast.LENGTH_SHORT).show();
final String CHANNEL_ID = "1";
if(Build.VERSION.SDK_INT = Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"001",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("description");
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
NotificationCompat.Builder notification = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle("dd")
.setSmallIcon(R.mipmap.ic_launcher);
notification.build();
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
managerCompat.notify(1,notification.build());
} else {
NotificationCompat.Builder notification = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle("dd")
.setSmallIcon(R.drawable.note)
.setChannelId(CHANNEL_ID);
notification.build();
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
managerCompat.notify(1,notification.build());
}
} }
Part of the code from the manifest:
<receiver android:name=".AlertReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".Services"/>

PendingIntent() is not public in PendingIntent; cannot be accessed from outside package

I know that this type of question asked but they are unable to solve my problem, Hence I am asking it again for having exact solution to my problem, I am using android studio 3.0.1 for creating simple notification application, when i run this application it shows me errors as show as follow:
Error:(40, 25) error: PendingIntent() is not public in PendingIntent; cannot be accessed from outside package
and my MainActivity.java as follow
package com.example.ram.notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int uniqueID = 45612;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
}
public void ClickNotification(View view){
//build the notification
notification.setSmallIcon(R.drawable.myimage);
notification.setTicker("this is the ticker");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Here is the title");
notification.setContentText("I am the body of your notificattion");
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = new PendingIntent().getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
//build notification and issues it
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
}
Please help me what should i do?
Simply delete "new" keyword in 40 row
must be
pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Trying to implement alarm with a notification

I am getting "The method getSystemService(String) is undefined for the type AlarmManagerBroadcastReceiver" error. I even tried to put getActivity() before it but it was of no help.
code for AlarmManagerBroadcastReceiver.java
package com.archana.pocketfriendly;
import java.text.Format;
import java.text.SimpleDateFormat;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
final public static String ONE_TIME = "onetime";
MediaPlayer alarm;
#Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
//Acquire the lock
wl.acquire();
//You can do the processing here update the widget/remote views.
Bundle extras = intent.getExtras();
StringBuilder msgStr = new StringBuilder();
if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
msgStr.append("One time Timer : ");
}
Format formatter = new SimpleDateFormat("hh:mm:ss a");
alarm = MediaPlayer.create(context, R.raw.alarm);
alarm.start();
msgStr.append("Do you want to enter the expenses?\nIgnore if already done!");
Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
Vibrator vib=(Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(2000);
// notification
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.settings)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainMenu.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainMenu.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); //error in this `enter code here`line.
mNotificationManager.notify(0, mBuilder.build());
//Release the lock
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 30 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 86400 , pi);
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
public void setOnetimeTimer(Context context){
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
}
}
Please let me know if any other information is required.
Just like your other calls to getSystemService, you need to perform it on a context object:
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

Categories