Search code examples
androidandroid-intentnotificationsandroid-pendingintent

How to call a non-activity method on Notification Click


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


Solution

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