如何在通知点击时调用非活动方法 [英] How to call a non-activity method on Notification Click
本文介绍了如何在通知点击时调用非活动方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Java类MyClass
,其中包含一个名为callMethod
的方法.当用户点击通知时,我想调用此方法
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);
}
});
}
}
下面是MyClass
public class MyClass {
public void callMethod(){
System.out.println("Notification clicked");
}
}
请帮助,我已经坚持了一段时间
Please help, I am stuck into this for a while now
推荐答案
您可以执行以下操作:
在创建要放入Notification
的PendingIntent
时:
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();
}
这篇关于如何在通知点击时调用非活动方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文