How to call a non-activity method on Notification

2019-06-24 08:18发布

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

2条回答
Anthone
2楼-- · 2019-06-24 08:49
 @Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    //notification callbacks here in activity
    //Call method here from non activity class.
    Classname.methodName();
}
查看更多
Anthone
3楼-- · 2019-06-24 09:08

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();
}
查看更多
登录 后发表回答