如何在通知单击上调用非活动方法

时间:2016-10-12 10:57:10

标签: android android-intent notifications android-pendingintent

我有一个java类MyClass,其中包含一个名为callMethod的方法。我想在用户点击通知时调用此方法

以下是我用于生成通知的代码

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

以下是MyClass

的实施
public class MyClass {
    public void callMethod(){
        System.out.println("Notification clicked");
    }
}

请帮助,我现在已经坚持了一段时间

2 个答案:

答案 0 :(得分:4)

你可以这样做:

创建PendingIntent以放入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);

现在,在MyClass.onCreate()

if (getIntent().hasExtra("fromNotification")) {
    callMethod();
}

答案 1 :(得分:1)

 @Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    //notification callbacks here in activity
    //Call method here from non activity class.
    Classname.methodName();
}