4

我正在自学如何在 Android 上使用 Phonegap 通知。虽然显示通知似乎是一个相当简单的过程

public void triggerTestNotification(String tag, int id,Context ctxt) 
{
  Intent notificationIntent = new Intent(context, PallActivity.class);
  notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 
  Intent.FLAG_ACTIVITY_CLEAR_TOP);

  notificationIntent.setAction(Intent.ACTION_MAIN);
  notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);

  PendingIntent contentIntent = PendingIntent.getActivity(ctxt, 0,  
  notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

  Notification not = new Notification.Builder(ctxt)
  .setContentTitle("Title").setContentText("Title")
  .setTicker("Tick tock")
  .setAutoCancel(true) 
  .setContentIntent(contentIntent)
  .setSmallIcon(ctxt.getApplicationInfo().icon).build();
   NotificationManager notificationManager = (NotificationManager)    
   ctxt.getSystemService(Context.NOTIFICATION_SERVICE);
   notificationManager.notify(tag, id, not);
 }

我发现更困难的是以下

  • 用户启动应用程序
  • 用户离开并开始做其他事情 - 应用程序是后台的
  • 通知到达
  • 被陈列
  • 用户点击通知。

此时应用程序应该回到前台。我以为我的意图代码

public class PallActivity extends Activity
{
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
   super.onCreate(savedInstanceState);
  finish();
  forceMainActivityReload();
 }

 private void forceMainActivityReload()
 {
  PackageManager pm = getPackageManager();
  Intent launchIntent =    
  pm.getLaunchIntentForPackage(getApplicationContext().getPackageName());           
  startActivity(launchIntent);
 }

 @Override
 protected void onResume() 
 {
  super.onResume();
  final NotificationManager notificationManager = (NotificationManager) 
  this.getSystemService(Context.NOTIFICATION_SERVICE);
  notificationManager.cancelAll();
 }

}

会处理这个,但它什么都不做。显然,我在这里遇到了问题 - 可能在 Intent 标志中。我将非常感谢任何能够让我走上正轨的人

4

1 回答 1

2

finish();从您的 oncreate 中删除,它会在您继续任何地方之前调用完成。

而不是开始 PallActivity,似乎您打算开始第二个活动或至少将 PallActivity 视为第二个活动。你不需要像那样从内部启动它forceMainActivityReload();。我将从通知意图开始您希望开始的活动,而不是使问题变得更加复杂和混乱。

notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;   
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

确保您使用的上下文是:

Context context = getApplicationContext();

并且,正如评论中提到的,从通知中删除这些:

notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);

如果需要,这里有更多详细信息:

单击通知时恢复活动

Android:如何从通知中恢复应用程序?

从通知中恢复活动

通知恢复活动

意图恢复先前暂停的活动(从通知中调用)

Android:从以前的位置恢复应用程序

如何使通知意图恢复而不是新的意图?

于 2016-05-16T17:17:04.570 回答