Using PendingIntent to reach my method - java

I have an android App that makes notifications. I can generate a notification together with a button, without a problem. My problem is the button's action. I want the button to call a method, for example a text-printing method. I'm using addAction(icon, "title", pendingIntent).
public void sendNotification(Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context.getApplicationContext(), SomeClass.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), (int) System.currentTimeMillis(), intent, 0);
NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon)
// This creates the button and it is using a pending intent.
.addAction(R.drawable.icon, "Print something", printPendingIntent)
// Clicking on notification takes you back to the App.
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setContentTitle("My Title")
.setContentText("Some text");
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
So the problem is in printPendingIntent, (no code written as you can see),
how do I access / call a method by using this pending intent?
Thanks for answers and sorry if the question is not clear and detailed enough.

add intent.putExtra("key","printmethod"); then receive the data in your SomeClass using getIntent().getExtras("Key"); if the value is matched then you can call your desired method in that activity.

Related

show a dialogfragment using notification

I have set up a notification like this in my .MainActivity class:
Intent downloadUpdateIntent = new Intent(mContext, updateAppDialogFragment.class);
PendingIntent downloadAppPendingIntent = PendingIntent.getActivity(mContext,0,downloadUpdateIntent,0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Update Available")
.setContentText("A new version of this app is available.")
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH)
.addAction(0,"Update",downloadAppPendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(mContext.NOTIFICATION_SERVICE);
notificationManager.notify(1, mBuilder.build());
What i need is to, when i click on update button, it should show updateAppDialogFragment to show an updating progress. When i generally use this class, i need to make such a call updateAppDialogFragment.newInstance(). But here, I cant understand how to accomplish this. Anyone to help?
I have very basic knowledge about intent. Actually, what i need to know is to use the intent to call a method.

Instead of pendingIntent, execute function in Notification.addAction() . Is it possible?

I want a method to be executed when I press a button on my notification. For that purpose I am adding an action with a PendingIntent to my notification:
Intent intent = new Intent(context, AlertActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Notification")
.setContentText("Click Here")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.addAction(R.mipmap.ic_launcher, "Test2", pendingIntent)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, notification);
That works, however I don't want to start an Activity when the user invokes the action. I just need to do some work.
For that purpose I implemented a Service which should be targeted by the PendingIntent instead:
public class MyServices extends IntentService {
public MyServices() {
super("MyServices");
}
#Override
protected void onHandleIntent(Intent intent) {
clearNotification();
}
public void clearNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(0);
Intent intent = new Intent(MyServices.this, MainActivity.class);
//Starting new activity just to check
startActivity(intent);
}
}
I create the PendingIntent like this:
final Intent intent = new Intent(context, MyServices.class);
final PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
However when I invoke the action on my notification nothing happens. What am I doing wrong?
A Notification is not part of your application. It is managed by the OS. It just so happens that there are APIs you can use to show/cancel/etc notifications.
A pending intent allows for external code (Notifications for example) to launch your app/activity/service/broadcastreceiver. This cannot be done without a pending intent.
What my task is to execute some piece of code when a specific action button is clicked, and clear notification; without starting any activity
You don't have to start an activity. You can do it in a broadcastreceiver that has no UI. Or, as CommonsWare suggested, use an IntentService, depending on what what you are doing in your "piece of code". IntentServices handle work in a separate thread.

Push Notifications - Android

I am working on a small project that involves a web interface that can send information to my android app which will display such information as Push Notifications.
But here is the thing, I am a bit confused with how to do that. As in what step will i have to take.
So I have a web interface in HTML which has a Textfield for notification Title, Content, and a submit button. I want it that when the user clicks the Submit button, the webpage will send the text that s in the Title and Content fields to my android app and then the app will just display them as push notifications.
So far on the app i have it that when you click a button on your device then it just shows a notification on the Actionbar. This is great for testing but It would be better that you can just compose your notification through a web interface.
My test Push Notification code for the app:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
// TODO: Make this accessible to exterior projects, such as web interface.
Notification notification = new Notification.Builder(MainActivity.this)
.setTicker("Notification")
.setContentTitle("Important Message")
.setContentText("This is an example of a push notification using a Navigation Manager")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nManager.notify(0, notification);
}
});
If anyone could be so kind to give me a hand, it would be much appreciated.
You are right, so far so good with the notification bar, now what you need is a notification service, and google has something like that for us...
how does this works??
Take a look at the image below,
you need to register your android app in the google service, and your web interface will need an id, so everytime you want to push something to the android, your web interface instead will push it to the google server with the Id of the app, then google (no matter how) will localize your app, and even if its not running, they will get the notification,
behind the scenes there is a couple of thing that you must do, bu nothing like launching rockets from the NASA.
I will suggest to take a look to some tutorials
in order to start with the registration of your app, get the api key etc etc..
Here is a great source in github which shows how you can add push notification service in your android app
github.com/rana01645/android-push-notification
Firstly read the full documentation
How to add push notification in android application from android studio – Android developer (part – 1 Connect with firebase ) ~ http://androidrace.com/2016/12/08/how-to-add-push-notification-in-android-application-from-android-studio-android-developer-part-1-connect-with-firebase/
How to add push notification in android application from android studio – Android developer (part – 2 Working with server) ~http://androidrace.com/2017/01/05/how-to-add-push-notification-in-android-application-from-android-studio-android-developer-part-2-working-with-server/
Then you can able to send push notification from your server using html
public class Uyarilar extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
Date currentTime = Calendar.getInstance().getTime();
showNotification(context);
}
private void showNotification(Context context) {
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.presta)
.setContentTitle("Saat 9:00")
.setContentText("Mesai saatiniz başlamıştır Lütfen harakete geçiniz!");
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
and call
private void setNotification() {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, 9);
calSet.set(Calendar.MINUTE, 00);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if (calSet.compareTo(calNow) <= 0) {
calSet.add(Calendar.DATE, 1);
}
Date currentTime = Calendar.getInstance().getTime();
Intent intent = new Intent(getBaseContext(), Uyarilar.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pendingIntent);
}
and
onCreate
setNotification();
this method to push notification
public void testMessage (String message , Intent intent){
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = "some_channel_id";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
android.support.v4.app.NotificationCompat.Builder notificationBuilder =
new android.support.v4.app.NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(getString(R.string.app_name))
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setBadgeIconType(android.support.v4.app.NotificationCompat.BADGE_ICON_SMALL)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
}
assert notificationManager != null;
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

I Have a notification in the status bar code, but AIDE is marking two things as wrong

I need to make a Status Bar Notification and I got this code from research, but it doesn't seem to be working out when I placed the code into MainActivity.java with AIDE
NotificationManager
mNotificationManager = (NotificationManager)
getSytemService(Context.N);
Notification notification = new notification(R.drawble.ic_launcher,
"Notification Test", System.currentT;
Context context = getApplicationContext();
CharSequence contentTitle = "My notification Title";
CharSequence contentText ="This is the message";
Intent notificationIntent = new Intent(this, MainActivity.class);
The errors seem to be at Line 3 with the (Context.N) where the N has the error message: Unknown member 'N' of 'android.content.Context'. The other error message is on the fifth line where it reads System.currentT with the error message of Unknown member 'currentT' of 'java.lang.Sytem'.
Context.N should be Context.NOTIFICATION_SERVICE.
System.currentT should be System.currentTimeMillis().
It seems that you are copying the code from somewhere but got the code truncated?
Here's a sample method for generating notifications.
This is based on Android's doc: Building a Notification. For more details (e.g. how to display a progress bar or an extended view), please read the docs.
private static void generateNotification(Context context, String messageTitle, String messageText)
{
// Get notification manager.
final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Setup notification builder.
final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(messageTitle)
.setContentText(messageText)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL);
// Create intent.
final Intent resultIntent = new Intent(context, MainActivity.class);
// Setup task stack builder.
final TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
taskStackBuilder.addParentStack(MainActivity.class);
taskStackBuilder.addNextIntent(resultIntent);
// Create pending intent.
final PendingIntent resultPendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Update notification builder.
notificationBuilder.setContentIntent(resultPendingIntent);
// Post notification.
notificationManager.notify(0, notificationBuilder.build());
}
The NotificationCompat.Builder class requires Android's version 4 Support Library.

notification opening a new window no matter what in Java Android

I want to launch a notification. When I click on it, it opens a NEW window of the app.
Here's my code:
public class Noficitation extends Activity {
NotificationManager nm;
static final int uniqueID = 1394885;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent= new Intent (Intent.ACTION_MAIN);
intent.setClass(getApplicationContext(), SchoolBlichActivity.class);
PendingIntent pi=PendingIntent.getActivity(this, 0, intent, 0);
String body = " body";
String title = "title!";
Notification n =new Notification(R.drawable.table, body, System.currentTimeMillis());
n.setLatestEventInfo(this, title, body, pi);
n.defaults = Notification.DEFAULT_ALL;
n.flags = Notification.FLAG_AUTO_CANCEL;
nm.notify(uniqueID,n);
finish();
}
by the way, if i add nm.cancel(uniqueID) before the finish(), it creates the notification and immediately deletes it...
Thanks for the help :D
You might want to just add a notification in the notification bar, and when the user clicks it, it will launch the actual Activity. This way the user won't be interrupted in whatever he's doing.
Create the status bar notification like this:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.notification_icon, "Hello", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, myclass.class);
notification.setLatestEventInfo(getApplicationContext(), "My notification", "Hello world!", notificationIntent, PendingIntent.getActivity(this, 0, notificationIntent, 0));
mNotificationManager.notify(1, notification);
http://developer.android.com/guide/topics/ui/notifiers/notifications.html
Are you just trying to open a notification window in a current activity? Because if you are I dont think you need to launch it with an intent. You normally only use intents to launch new services or activities in your app unless youve built a custom view and activity/service which is to take place within the notification box. I see you have it set up in its own class which is fine but I think the way your doing it by default would open an entire new view.
If you need to launch a notification during a process or something like a button click you dont need to have the intent there.....or at least I never did :) What exactly are you trying to achieve with the notification.

Categories