在通知点击Android的调用方法通知、方法、Android

2023-09-12 22:15:28 作者:你的眼似湛蓝的海

这code创建一个通知。如果你点击它,目前的应用程序运行(目的是在输入,这只是我的活动创建) ,一个Android开发者博客上稍作修改的版本:

this code creates a notification. If you click it, the current application is ran (the intent is created in Entry, which is my only Activity), a slightly modified version of a Android Developers blog:

private void makeIntent() { 
    NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    Notification note = new Notification(R.drawable.prev, "Status message!", System.currentTimeMillis());
    Intent intent = new Intent(this, Entry.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0,intent, 0);
    note.setLatestEventInfo(this, "New Email", "Unread Conversation", pi);
    note.flags |= Notification.FLAG_AUTO_CANCEL;            
    mgr.notify(NOTIFY_ME_ID, note);
}

但我不希望启动任何活动,而仅仅是运行在当前活动的方法。从我至今读,我想我必须使用像 startActivityForResult方法(),使用意图过滤器和实施 onActivityResult(),但瞎搞所有这些事情,改变的东西后,意图 PendingIntent ,我仍然没有可用的结果。是否有可能以某种方式只需要调用在输入的方法(我的主要活动,其中意图创建),或捕捉任何输出或输入意图当我点击我的新作通知

But I don't want to start any activity, but merely to run a method in the current activity. From what I've read so far, I guess I have to use methods like startActivityForResult(), use intent-filters and implement onActivityResult(), but after messing around with all those things, changing things in the Intent and PendingIntent, I still have no usable result. Is it possible to somehow just call a method in Entry (my Main Activity, in which the Intent is created), or catch any outgoing or incoming Intents when I click my newly made Notification?

PS。我的道歉,如果这是一个重复线程,因此是相当缓慢的,现在,我不能搜索正确。

PS. my apologies if this is a duplicate thread, SO is quite slow right now, I can't search properly.

推荐答案

添加安卓launchMode =singleTop活动在你的清单,有法保护无效onNewIntent(意向意图){...} 并使用此code:

Add android:launchMode="singleTop" in your activity in your Manifest, have the method protected void onNewIntent(Intent intent) { ... } and use this code:

private static final int MY_NOTIFICATION_ID=1;
private NotificationManager notificationManager;
private Notification myNotification;

void notification() {   
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    myNotification = new Notification(R.drawable.next, "Notification!", System.currentTimeMillis());
    Context context = getApplicationContext();
    String notificationTitle = "Exercise of Notification!";
    String notificationText = "http://android-er.blogspot.com/";
    Intent myIntent = new Intent(this, YourActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(YourActivity.this, 0,   myIntent, Intent.FILL_IN_ACTION);
    myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
    myNotification.setLatestEventInfo(context, notificationTitle, notificationText, pendingIntent);
    notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}