【问题标题】:How to switch between Android apps programmatically如何以编程方式在 Android 应用程序之间切换
【发布时间】:2019-11-02 15:21:22
【问题描述】:

出于调试目的,我想在两个正在运行的 Android 应用程序(客户端和服务器)之间快速切换。两者通过套接字连接进行连接。理想情况下,我想为两者添加一个按钮以切换到另一个(保留连接),以便我可以轻松查看两端发生的情况。

这是我尝试过的:

  • 使用“最近使用的应用程序”按钮
    这工作得很好,但有点尴尬,尤其是在堆栈很大的情况下。

  • 使用分屏
    这也很好,但小屏幕有问题

  • 尝试过第三方应用切换器,但不喜欢这些。

  • 按包名称尝试 startActivity(单击按钮时)
    这将是我的首选解决方案,但有问题。切换好,但每次创建新任务时,启动并推送到堆栈(不保留连接)。代码如下:

    void switchToClient()       // from Server (on Button click)
    {
        // Alternative Flags Tried: none, FLAG_ACTIVITY_SINGLE_TOP, FLAG_ACTIVITY_NEW_TASK, other
        Intent intent;
        intent = this.getPackageManager().getLaunchIntentForPackage( "com.example.Client" );
        intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
        startActivity( intent );
    }  
    

【问题讨论】:

    标签: android start-activity android-recents split-screen-multitasking


    【解决方案1】:

    我终于知道如何在应用之间切换 以编程方式(保持其状态)。在每个应用程序中,我使用“getTaskId()”获取其任务 ID 并将其保存到 /sdcard/ 上的文件中。

    然后,在每个应用程序中,单击按钮,我调用

    void switchTask()
    {
      int tid;
      ActivityManager am;
      am = (ActivityManager)Ctx.getSystemService( Context.ACTIVITY_SERVICE );
      tid = getPkgTaskId();  // read task id of *other* app from file
      am.moveTaskToFront( tid, 0, null );
    }
    

    注意:这些需要权限:

    • READ_EXTERNAL_STORAGE
    • WRITE_EXTERNAL_STORAGE
    • REORDER_TASKS

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多