Android-Notification doesn't appear - java

This is a code for creating a notification by click a button and then turn to another class. The second class it totally empty. I don't know why it doesn't appear even it cannot turn to another class.
I have already checked the "sittings" of this file and the "notification" is "on". Could anyone help me to check it?
MainActivity.class
package com.example.ww.lab;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.NotificationManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private int id = 1;
private NotificationCompat.Builder notification_builder;
private NotificationManagerCompat notification_manager;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notification_manager.notify(id, notification_builder.build());
}
});
Intent open_activity_intent = new Intent(this, NotificationActivity.class);
PendingIntent pending_intent = PendingIntent
.getActivity(this, 0, open_activity_intent, PendingIntent.FLAG_CANCEL_CURRENT);
notification_builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notification Title")
.setContentText("Notification Body")
.setAutoCancel(true)
.setContentIntent(pending_intent);
notification_manager = NotificationManagerCompat.from(this);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ww.lab.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do it!"
android:id="#+id/button"
android:onClick="sendNotification"/>
</android.support.constraint.ConstraintLayout>

As you have stated your compiled sdk version is 26. You need to set Channel of your notification before posting it. So it will be like
NotificationManager notification_manager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String chanel_id = "3000";
CharSequence name = "Channel Name";
String description = "Chanel Description";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(chanel_id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
notification_manager.createNotificationChannel(mChannel);
notification_builder = new NotificationCompat.Builder(this, chanel_id)
} else {
notification_builder = new NotificationCompat.Builder(this);
}
notification_builder.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notification Title")
.setContentText("Notification Body")
.setAutoCancel(true)
.setContentIntent(pending_intent);
For more please visit Developer Site

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());
}
}

Service does not execute when app is closed, but it does execute when it's in the background

I have been trying to make an alarm application. I have been struggling with making a full screen notification. I finally did manage to do it, but it only works when the app is running in the background.
It also needs to work when you have closed the app. I don't understand what I am supposed to do to achieve this. I know it is possible because my alarm clock app I use every day is able to do this.
Mainactivity.java
package com.example.wekkerapp;
import java.util.Calendar;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String CHANNEL_ID = "my_channel";
static final String FULL_SCREEN_ACTION = "full_screen_action";
static final int NOTIFICATION_ID = 1;
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Alarm";
String description = "Het alarm gaat";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("2", name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = (NotificationManager) getSystemService(this.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
createNotificationChannel(this);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TimePicker klok = findViewById(R.id.timePicker1);
klok.setIs24HourView(true);
final Button getTimeBtn = findViewById(R.id.getTimeBtn);
final TextView showText = findViewById(R.id.showText);
final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
getTimeBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Intent intent = new Intent(FULL_SCREEN_ACTION, null, getApplicationContext(), WekkerService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
int uur = klok.getHour();
int minuut = klok.getMinute();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, uur);
cal.set(Calendar.MINUTE, minuut);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Toast.makeText(getApplication().getApplicationContext(), "Alarm gaat om " + uur + ":" + minuut,Toast.LENGTH_LONG).show();
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
showText.setText(Integer.toString(uur) + ':' + Integer.toString(minuut));
NotificationManagerCompat.from(getApplicationContext()).cancel(NOTIFICATION_ID);
}
});
}
static void CreateFullScreenNotification(Context context) {
Intent intent = new Intent(context, MainActivity2.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Alarm")
.setContentText("Het alarm gaat")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setContentIntent(pendingIntent)
.setFullScreenIntent(pendingIntent, true);
NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notificationBuilder.build());
}
private static void createNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "channel_name", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("channel_description");
notificationManager.createNotificationChannel(channel);
}
}
}
}
Wekkerservice.java
package com.example.wekkerapp;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
import androidx.annotation.Nullable;
public class WekkerService extends IntentService {
public static MediaPlayer mediaPlayer;
public WekkerService() {
super("WekkerService");
}
#Override
public void onCreate() {
super.onCreate(); // if you override onCreate(), make sure to call super().
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Log.d("test", "onHandleIntent: ");
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.alarmpie);
if (MainActivity.FULL_SCREEN_ACTION.equals(intent.getAction()))
mediaPlayer.setLooping(true);
mediaPlayer.start(); // no need to call prepare(); create() does that for you
MainActivity.CreateFullScreenNotification(getApplicationContext());
}
}
Mainactivity2.java
package com.example.wekkerapp;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NotificationCompat;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button stopbutton = findViewById(R.id.button2);
stopbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WekkerService.mediaPlayer.stop();
}
});
}
}
I would suggest you use a BroadcastReceiver and then start the service from its onReceive method.
So in your MainActivity's onClick listener you should change the following pending intent
as follows:
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
to
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
and the intent you pass in should launch a BroadcastReceiver.
Immediately after the BroadcastReceiver is launched by the alarm manager, you should start the service from its onReceive method.
Remember that due to the recent changes the OS won't just let you start a service or background service just whenever and however you want!
If the app is closed and you want to start the service, you SHOULD start it as a ForgroundService and show a notification(you have 5 seconds to make this call) otherwise it will throw RemoteServiceException and that's why the code in your service will not run.
I highly encourage you to take a look at this answer:
https://stackoverflow.com/a/56471104/9023032
Here is also another useful answer which might become handy:
https://stackoverflow.com/a/54035247/9023032

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);

Android Status Bar Notification Not Loading

I'm hoping this issue is simply something to do with the emulator, basically ive got a Service that sets a timer, as soon as the timertask runs the following code is supposed to execute:
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns);
int icon = R.drawable.androidapplogo;
CharSequence tickerText = "Ticker Text";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "My Notification";
CharSequence contentText = "Hello World!";
//Do i need this?
Intent notificationIntent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, null);
mNotificationManager.notify(1, notification);
The issue i have, is that when the notification gets called, it appears in the status bar, but when i click on the icon, it just has a blue circle. I dont own an android phone so im guessing that means its trying to load something.
Btw, ive pretty much lifted the code from here: http://developer.android.com/guide/topics/ui/notifiers/notifications.html
So my question is two fold:
- What is happening, is it failing to load something?
- Any ideas on how to fix it, or would it be worth finding a new form of notification
EDIT: Im sorry guys, found the issue was that you needed to drag down the Notification Window - i rarely use android x)
package com.androidtest.notification;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SimpleNotification extends Activity {
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
final Notification notifyDetails = new Notification(R.drawable.android,
"New Alert, Click Me!", System.currentTimeMillis());
Button start = (Button) findViewById(R.id.notifyButton);
Button cancel = (Button) findViewById(R.id.cancelButton);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Context context = getApplicationContext();
CharSequence contentTitle = "TITLES....";
CharSequence contentText = "TEXT FOR DETAIL";
Intent notifyIntent = new Intent(
android.content.Intent.ACTION_VIEW, Uri
.parse("CONTACT NO / OR ANY OTHER ACTION WHICH YOU WANT ON NOTIfic. ICON TAP"));
PendingIntent intent = PendingIntent.getActivity(
SimpleNotification.this, 0, notifyIntent,
android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.setLatestEventInfo(context, contentTitle,
contentText, intent);
mNotificationManager.notify(SIMPLE_NOTFICATION_ID,
notifyDetails);
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
}
});
}
}
XML Test file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/notifyButton"
android:text="#string/notify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
></Button>
<Button
android:id="#+id/cancelButton"
android:text="#string/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
></Button>
</LinearLayout>
pending intent to call some intent on notification tap..gve ans frm whtevr i understand ur quest
leave comment if any prob with the code...

The constructor Intent is undefined

I have the content module loaded, the specific error I'm getting is: The constructor Intent(new View.OnClickListener(){}, Class<ContactWidget>) is undefined
Any ideas on this? I got this from the tutorial here: http://developer.android.com/guide/topics/ui/notifiers/notifications.html
package com.example.contactwidget;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ContactWidget extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button calc1 = (Button) findViewById(R.id.calc_button_1);
calc1.setOnClickListener(buttonListener);
setContentView(R.layout.main);
}
private static final int HELLO_ID = 1;
private OnClickListener buttonListener = new OnClickListener() {
public void onClick (View v) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.icon;
CharSequence ticketBrief = "Button Pressed Brief";
CharSequence ticketTitle = "Button pressed";
CharSequence ticketText = "You pressed button 1";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, ticketBrief, when);
Intent notificationIntent = new Intent(this, ContactWidget.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), ticketTitle, ticketText, contentIntent);
mNotificationManager.notify(HELLO_ID, notification);
}
};
}
Change this:
new Intent(this, ContactWidget.class);
to
new Intent(ContactWidget.this, ContactWidget.class);
The error happens because, in that case, this is referencing the instance of OnClickListener, but the Intent's constructor expects a Context. The context you have to pass is the reference to the activity itself, thus you have to access it explicitly using ContactWidget.this.
The context passed in could be from a remote application host... apparently you need the app context from your app, the one with your class (your broadcast reciever for instance).
Intent intent = new Intent(context.getApplicationContext(), WidgetryBroadcastReceiver.class);
instead of
Intent intent = new Intent(context, WidgetryBroadcastReceiver.class);
go figure.
yeah that workerd for me aswell for the error in
Geocoder gc = new Geocoder(this, Locale.getDefault());

Categories