重复使用相同的 activity

Re-use the same activity

想象一下这种堆栈情况: A - B- C - D - B ,A、B 和 C 是活动,但 D 是服务。

基本上,我有一个服务 (D),我想从该服务调用一个已经存在的 activity (B)。

我知道如果我想重新使用 activity,我所要做的就是使用标志(或更改清单)SingleTop(将重新使用 activity如果它已经在顶部)或 SingleTask(将重新使用 activity 无论它是否在顶部)。

问题是因为我在服务中,所以我必须添加标志 FLAG_ACTIVITY_NEW_TASK,这样我才能调用 activity。此外,我在我的清单中添加了 SingleTask 作为启动模式,以便 activity 将被重新使用。

这很好用,因为它重新使用相同的 activity 并返回到 onNewIntent(Intent intent) 方法。 问题是我在该意图上附加的所有内容都为空。我尝试通过该意图发送 2 个字符串和 2 个布尔值,它们都以 null 形式到达 onNewIntent(Intent intent)。

我该如何解决这个问题?在获得附加功能之前,我是否必须在 onNewIntent(Intent intent) 方法中做一些事情?有没有更好的选择?

PS: 我听说过 StartActivityForResult 或类似的东西。这只会在 50% 的情况下起作用,因为这是针对“类似聊天”的应用程序。

所以我会在 "chat" 上,从那里去另一个 activity,在那里我可以 select 发送一些东西。在那之后,我会去服务,在那里完成传输,然后回到"chat"。 但是当我收到东西时,我已经在 "chat" 上了,所以在这种情况下 startActivityForResult 将不起作用(要接收的服务将在后台 运行 + 我不想完成接收部分,因为我想一直在听一些东西。

这是我尝试重新启动单个 activity 的服务的代码:

      Intent transfRec=new Intent(ServerComm.this ,TransferRecordActivity.class);
                            transfRec.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                            transfRec.putExtra("receivedFilePath",appName+".apk");
                            transfRec.putExtra("joinMode","appselection");
                            transfRec.putExtra("nameOfTheApp",appName);
                            transfRec.putExtra("received",false);

                            transfRec.putExtra("isHotspot",isHotspot);
                            startActivity(transfRec);

这是我的 onNewIntent(Intent intent) 的代码:

 protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    System.out.println("I am here in the new intent");
  if(intent==null){
        System.out.println("Intent is null inside the new intent method !!!");
    }
    tmpFilePath=getIntent().getStringExtra("receivedFilePath");
    System.out.println("The tmpFilePath is : "+tmpFilePath);
    received=getIntent().getBooleanExtra("received",true);
    nameOfTheApp=getIntent().getStringExtra("nameOfTheApp");
    isHotspot=getIntent().getStringExtra("isHotspot");
    System.out.println("O received boolean esta a  : : : "+received);
    textView.setVisibility(View.GONE);

    receivedFilePath= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+tmpFilePath;
    System.out.println("transfer REcord Activity _: the received file path is :::: " +receivedFilePath);

    getReceivedApps();

    adapter= new HighwayTransferRecordCustomAdapter(this,listOfItems);
    receivedAppListView.setAdapter(adapter);

编辑:正如你们所看到的,我检查了意图是否为空,事实并非如此,因为它不执行那种情况下的 system.out.println!

问题是您在 onNewIntent() 中调用 getIntent()。来自 getIntent():

的文档

Return the intent that started this activity.

因此,您得到 intent 提供给 onCreate()。要获得提供给 onNewIntent()intent,您只需使用方法签名中提供的 intent

protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    tmpFilePath=intent.getStringExtra("receivedFilePath");
    ...
}