I'm working on a custom notification for Android Wear that should display a custom activity when the notification is swiped upwards. The notification is displayed, and even the wearable features (like the background and custom size) are visible, however the activity is never loaded nor displayed.
Also, MainActivity and PlaybackNotificationActivity should both write a message to the log when they're created. MainActivity writes the message, but the latter doesn't.
What could be the problem?
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new NotificationBuilder(this).showNotification();
Log.e("MainActivity", "Reached");
finish();
}
}
NotificationBuilder.java
public class NotificationBuilder {
private final Context mContext;
public NotificationBuilder(Context context) {
mContext = context;
}
public Notification buildNotification() {
Notification.Builder builder = new Notification.Builder(mContext)
.setContentTitle("Title")
.setContentText("Content text")
.setSmallIcon(R.mipmap.ic_launcher);
Intent playbackIntent = new Intent(mContext, PlaybackNotificationActivity.class);
PendingIntent playbackPendingIntent = PendingIntent.getActivity(
mContext, 0, playbackIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.WearableExtender extender = new Notification.WearableExtender()
.setBackground(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
.setCustomSizePreset(Notification.WearableExtender.SIZE_MEDIUM)
.setDisplayIntent(playbackPendingIntent);
builder.extend(extender);
return builder.build();
}
public void showNotification() {
Notification notification = buildNotification();
NotificationManager manager = (NotificationManager)
mContext.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, notification);
}
}
PlaybackNotificationActivity.java
public class PlaybackNotificationActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playback_notification);
Log.e("NotificationActivity", "Reached");
Toast.makeText(this, "Toast", Toast.LENGTH_SHORT).show();
}
}
It turns out that the emulator for Android Wear is to blame, it works perfectly on a physical smartwatch but not on the emulator.
Related
As the title implies, how can I prevent my app from getting notifications when I'm in the desired activity? I'm developing a chat application wherein users can get notifications when a new message has been posted, how can I prevent the notification when the user is in the chat activity?
here's FirebaseMessagingService:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(#NonNull RemoteMessage message) {
super.onMessageReceived(message);
int requestID = (int) System.currentTimeMillis();
String title = message.getNotification().getTitle();
String body = message.getNotification().getBody();
String click_action=message.getNotification().getClickAction();
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(),"Notification");
builder.setContentTitle(title);
builder.setContentText(body);
builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
builder.setLights(getResources().getColor(R.color.chitchat), 3000, 3000);
builder.setSmallIcon(R.drawable.logowhite);
Intent intent = null;
//message.getData().get("type");
if (Objects.requireNonNull(message.getData().get("type")).equalsIgnoreCase("privatechat"))
{
intent = new Intent(click_action);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("GCKey", message.getData().get("GCKey"));
intent.putExtra("GCNameKey", message.getData().get("GCNameKey"));
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestID, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE );
builder.setAutoCancel(true);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("Notification", "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(69, builder.build());
}
}
It should not be hard. You can just create a class where you have a static variable where you just set the activity and before notifying, check whether you want to show notification or not. This would go this way:
Make a new class with a static variable
public class NotificationHelper {
public static boolean shouldShowNotification = true;
}
In the activity you don't want the notification to show in add this code:
#Override
public void onResume(){
super.onResume();
NotificationHelper.shouldShowNotification = false;
}
#Override
public void onPause(){
super.onPause();
NotificationHelper.shouldShowNotification = true;
}
In the MyFirebaseMessagingService class, add a condition to before executing the code.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(#NonNull RemoteMessage message) {
super.onMessageReceived(message);
if(NotificationHelper.shouldShowNotification){
// your code goes here...
}
}
}
I am new to android programming and just started working on my first app recently. I am trying to create a daily notification that a user would get at the same time every day. I've looked through documentation and some tutorials and came up with this. For some reason the code below does not work. It has no errors, runs just fine, but doesn't do the job and I can't seem to find the problem. There is also some code that is responsible for re-scheduling notifications when the device restarts but I don't think the problem lies there since I don't even get the initial notifications.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (Button)findViewById(R.id.btn_show);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAlarm(true,true);
}
});
myWebView = (WebView)findViewById(R.id.webView1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://google.com");
myWebView.setWebViewClient(new WebViewClient());
}
private void startAlarm(boolean isNotification, boolean isRepeat) {
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent myIntent;
PendingIntent pendingIntent;
// SET TIME HERE
Calendar calendar= Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,14);
calendar.set(Calendar.MINUTE,45);
myIntent = new Intent(MainActivity.this,AlarmNotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,0);
if(!isRepeat)
manager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+3000,pendingIntent);
else
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
}
AlarmNotificationReciever.Java
public class AlarmNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Intent myIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
0,
myIntent,
FLAG_ONE_SHOT );
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Zodiac")
.setContentIntent(pendingIntent)
.setContentText("Check out your horoscope")
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
.setContentInfo("Info");
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
}
It should basically schedule a notification at 14:45 after pressing the button but for some reason it doesn't.
Since Android Oreo, implicit broadcast receivers won’t work when
registered in the AndroidManifest.xml
To use Implicit Receivers in your application, you need to define them programmatically in your code, using
registerReceiver().
3.Using registerReceiver() we can programmatically register and unregisterReceiver() during the lifecycle of the activity. This way
implicit receivers would only be called when our
activity/application is alive and not at other times.
we working fine:
[public class MainActivity extends AppCompatActivity {
Button show;
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// register custom intent filter
*registerReceiver(new AlarmNotificationReceiver(),new IntentFilter(Intent.ACTION_BATTERY_CHANGED));*
\[enter image description here\]\[1\]
show = (Button)findViewById(R.id.btn_show);
show.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View v) {
startAlarm(true,true);
}
});
myWebView = (WebView)findViewById(R.id.webView1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://google.com");
myWebView.setWebViewClient(new WebViewClient());
}
#RequiresApi(api = Build.VERSION_CODES.N)
private void startAlarm(boolean isNotification, boolean isRepeat) {
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent myIntent;
PendingIntent pendingIntent;
// SET TIME HERE
Calendar calendar= Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,14);
calendar.set(Calendar.MINUTE,45);
myIntent = new Intent(MainActivity.this,AlarmNotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,0);
if(!isRepeat)
manager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+3000,pendingIntent);
else
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
}
}][1]
1)But the above code may not work in all versions i.e notofication will not came oreo(8.0) and above.beacause of NotificationBuilder is depricated and background execution limits.Go to
2)Use Notification Channel .like below
use this code.hope its works fine!!!
void issueNotification()
{
// make the channel. The method has been discussed before.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
makeNotificationChannel("CHANNEL_1", "Example channel", NotificationManager.IMPORTANCE_DEFAULT);
}
// the check ensures that the channel will only be made
// if the device is running Android 8+
NotificationCompat.Builder notification =
new NotificationCompat.Builder(this, "CHANNEL_1");
// the second parameter is the channel id.
// it should be the same as passed to the makeNotificationChannel() method
notification
.setSmallIcon(R.mipmap.ic_launcher) // can use any other icon
.setContentTitle("Notification!")
.setContentText("This is an Oreo notification!")
.setNumber(3); // this shows a number in the notification dots
NotificationManager notificationManager =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(1, notification.build());
// it is better to not use 0 as notification id, so used 1.
}
When I press the notification the activity opens, but when I click back the App go to background and still on the same activity.
I wanna go back to MainActivity when I click back. what's wrong in my code?
public class MainActivity extends AppCompatActivity {
NotificationManagerCompat notificationManager;
NotificationCompat.Builder n;
String ID = "a" ;
int id=1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void b2(View view) {
Intent i = new Intent(MainActivity.this, Main2.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(i);
PendingIntent pi = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
n = new NotificationCompat.Builder(this, ID)
.setSmallIcon(R.drawable.xx)
.setContentTitle("don't forget")
.setContentText("Hello0o0o0o")
.setContentIntent(pi)
.setAutoCancel(true);
notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(id , n.build());
id++;
}
public void b1(View view) {
Intent i4 = new Intent(this,Read.class);
startActivity(i4);
}
}
From your code I don't see the problem, but you could override the onBackPressed() function to move back to MainActivity. It's a solution. Also check if you actually are calling this function b2.
I am implementing FCM(Firebase cloud messaging) for push notifications. I could get push notification from the server using my service class successfully. But, how do I send data(messages) from the service class to the activity?
Service.java
public class Service extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, FCMActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri =RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setLights(Color.RED, 1000, 300);
NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
FCMActivity.java
public class FCMActivity extends AppCompatActivity {
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fcm);
mTextView = (TextView) findViewById(R.id.txt);
}
}
There are several options, among those are:
Register a BroadcastReceiver inside your Activity with an IntentFilter for your custom action (action is just a String identifier for a broadcast message type), and send the broadcast from service using LocalBroadcastManager.getInstance().sendBroadcast(Intent intent) method
Use an event bus, for example the very popular GreenRobot EventBus library. See https://github.com/greenrobot/EventBus#eventbus-in-3-steps for explanation.
Both of these options require registering and unregistering a listener / receiver inside your Activity, which is best done in onResume/onPause for events that should trigger UI changes.
Additionally, you can bind to the service from your Activity.
You should use IBinder in your service and ServiceConnection in your Activity
I'm trying to create a custom notification with ImageButton.
When onclicked, the ImageButton should start an activity named TaskActivity, but i'm unable to achieve this.
The followings are my codes:
MainActivity.java
public void onCreate(Bundle savedInstanceState) {
//button intents
Intent cmdIntent = new Intent(
MainActivity.this, cmdButtonListener.class);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(
MainActivity.this, 0, cmdIntent, 0);
//notification mgr
int notifyID = 001;
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotifyMgr = (NotificationManager)getSystemService(ns);
//new notification
int icon = R.drawable.icon3;
long when = System.currentTimeMillis();
#SuppressWarnings({ "deprecation" })
Notification notify = new Notification(icon,getString(R.string.text),when);
//remote views
RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.custom_notification);
contentView.setImageViewResource(R.id.notification_image, R.drawable.icon4);
contentView.setTextViewText(R.id.notification_title, "APP TITLE");
contentView.setTextViewText(R.id.notification_text, "hello");
contentView.setOnClickPendingIntent(R.id.notification_image, pendingSwitchIntent);
notify.contentView = contentView; //set
//notification intent
Intent nIntent = new Intent(MainActivity.this,MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, nIntent, 0);
notify.contentIntent = contentIntent;
mNotifyMgr.notify(notifyID,notify);
}
public class cmdButtonListener extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent){
System.out.println("Here, I am here");
Intent newAct = new Intent(MainActivity.this, TaskActivity.class);
startActivity(newAct);
}
}
Android Manifest
<receiver android:name=".MainActivity$cmdButtonListener" />
I dont know, where i'm wrong as i'm doing exactly as it is shown in most of the tutorials online. :(
Finally I've found a solution...
Declare the below variable
private static Context mContext;
Add below code inside public void onCreate(Bundle savedInstanceState) {
mContext = this;
Finally, change the below piece of code in public class cmdButtonListener extends BroadcastReceiver{
Intent newAct = new Intent(MainActivity.this, TaskActivity.class);
startActivity(newAct);
To
Intent Act = new Intent(mContext,TaskActivity.class);
mContext.startActivity(Act);