I have a java class MyClass
which contains a method called callMethod
. I want to call this method when user clicks on the notification
Below is the code i used to generate the notification
public class MainActivity extends AppCompatActivity {
Button button;
NotificationManager mNotifyMgr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
mNotifyMgr = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, new Intent(MainActivity.this, MyClass.class), PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification =
new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("Notification")
.setSmallIcon(R.drawable.ic_launcher)
.setContentText("Downloaded")
.setContentIntent(pendingIntent)
.build();
mNotifyMgr.notify(1,notification);
}
});
}
}
And below is the implementation of MyClass
public class MyClass {
public void callMethod(){
System.out.println("Notification clicked");
}
}
Please help, I am stuck into this for a while now
use interface to communicate with activity from non activity class. create colorChange() in interface and get the instance of interface in non activity class and call that method.
We can send the data using the putExtra() method from one activity and get the data from the second activity using the getStringExtra() method.
A notification is a message that Android displays outside your app's UI to provide the user with reminders, communication from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification.
You could do something like this:
When creating your PendingIntent
to put in the Notification
:
Intent notificationIntent = new Intent(MainActivity.this, MyClass.class);
notificationIntent.putExtra("fromNotification", true);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Now, in MyClass.onCreate()
:
if (getIntent().hasExtra("fromNotification")) {
callMethod();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//notification callbacks here in activity
//Call method here from non activity class.
Classname.methodName();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With