首页 \ 问答 \ 从Intent.createChooser()启动时如何防止多个app / activity实例?(How to prevent multiple instances of app/activity when it is started from Intent.createChooser()?)

从Intent.createChooser()启动时如何防止多个app / activity实例?(How to prevent multiple instances of app/activity when it is started from Intent.createChooser()?)

我有一个带有单个TextView的简单应用程序,它显示来自ACTION_SEND意图的纯文本。 我的问题是,每次向此应用程序共享某些文本时,都会创建一个新实例。 我可以在检查最近的应用时看到该应用的多个实例。 我在API 23上测试它。

这是我的代码:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("MainActivity.java", "onCreate");

        ((TextView) findViewById(R.id.temp_textview)).setText("Share text/links from other apps");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        String action = intent.getAction();
        intent.getFlags();
        Log.d("onResume - intent: ",intent.toString());
        String type = intent.getType();
        TextView displayText = (TextView) findViewById(R.id.temp_textview);

        if (Intent.ACTION_SEND.equals(action) && type!=null) {
            Log.d("MainActivity.java", "Intent verified");
            if ("text/plain".equals(type)) {
                handleSendText(intent, displayText);
            }
        }
    }

    void handleSendText(Intent intent, TextView displayText) {
        String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
        Log.d("MainActivity.java", sharedText);
        if (sharedText != null) {
            displayText.setText(sharedText);
        }
    }
}

我试图摆弄清单中的launchMode但没有一个选项解决了这个问题。

编辑1:

这是我的清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="chaitanya.im.example">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I have a simple app with a single TextView which displays plain text from an ACTION_SEND intent. My issue is that every time that some text is shared to this app a new instance is created. I can see multiple instances of the app on checking the recent apps. I'm testing it on API 23.

This is my code:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("MainActivity.java", "onCreate");

        ((TextView) findViewById(R.id.temp_textview)).setText("Share text/links from other apps");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        String action = intent.getAction();
        intent.getFlags();
        Log.d("onResume - intent: ",intent.toString());
        String type = intent.getType();
        TextView displayText = (TextView) findViewById(R.id.temp_textview);

        if (Intent.ACTION_SEND.equals(action) && type!=null) {
            Log.d("MainActivity.java", "Intent verified");
            if ("text/plain".equals(type)) {
                handleSendText(intent, displayText);
            }
        }
    }

    void handleSendText(Intent intent, TextView displayText) {
        String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
        Log.d("MainActivity.java", sharedText);
        if (sharedText != null) {
            displayText.setText(sharedText);
        }
    }
}

I have tried fiddling with the launchMode in the manifest but none of the options solved the issue.

Edit 1:

Here's my manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="chaitanya.im.example">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />
            </intent-filter>
        </activity>
    </application>

</manifest>

原文:https://stackoverflow.com/questions/37679848
更新时间:2022-06-22 20:06

最满意答案

为什么他们的括号包含在变量i中?
为什么删除[] p而不是变量p?

 p= new (nothrow) int [i];

动态分配i元素的int数组。

 delete []p;

删除动态分配的数组。


C ++中动态分配的基本规则是:

  • 如果使用new来动态分配内存,请使用delete取消分配内存。
  • 如果使用new []动态分配内存,请使用delete []取消分配。

另外,请注意您正在使用new运算符的nothrow版本,如果出现某些错误情况并且不抛出异常,它基本上返回null ,这允许C ++代码与在内存分配后使用null检查的旧c代码兼容(malloc在失败时返回null)。


for语句究竟做了什么?

for语句是一个条件循环结构 ,它继续执行循环,直到condition保持为真。 for循环的基本语法是:

for(;condition;)
{ 
    //doSomething
}

为什么他们的2个陈述?
代码中的第一个for loop获取用户的输入。 它需要输入i次。

第二个for loop打印出数组的内容。


建议你学习一本好的C ++书籍并阅读基础知识以了解更多信息。


why is their a bracket enclosed in variable i? &
Why is it deleting []p instead of the variable p?

 p= new (nothrow) int [i];

Dynamically Allocates an int array of i elements .

 delete []p;

Deletes the dynamically allocated array.


Basic Rules of dynamic allocation in C++ are:

  • If you use new to dynamically allocate memory, Use delete to deallocate it.
  • If you use new [] to dynamically allocate memory, Use delete [] to deallocate it.

Also, note that you are using nothrow version of the new operator, it basically returns a null if some error condition and does not throw an exception, this allows the C++ code to be compatible with the legacy c code which uses null check after memory allocations(malloc returns null on failure).


what does a for statement do exactly?

A for statement is a conditional loop construct, It keeps on executing the loop untill the condition remains true. The basic syntax of for loop is:

for(;condition;)
{ 
    //doSomething
}

why are their 2 for statements?
The first for loop in your code gets the input from the user. It takes the input for i times.

The second for loop prints out the contents of the array.


Suggest you to pick up a good C++ book and read through the basics to understand more.

相关问答

更多
  • 检查代码项目页面的谷歌夏季! 这些都是开源的,其中很多都基于C / C ++。 每个项目都列出了针对外部人员/初学者的想法。 以下是去年的页面: http : //code.google.com/soc/2008/ Google尚未决定哪些项目今年参与,但这些信息将在未来几周内发布(在3月2009)以及一个新的想法列表。 如果你是一所学院/大学的学生,那么你很幸运,甚至可以通过GSOC项目获得指导。 但即使不是,他们也会非常重视您可以做出的任何贡献。 Check the google summer of c ...
  • 指针 取消引用NULL指针 取消引用由大小为零的“新”分配返回的指针 使用指向生命周期结束的对象的指针(例如,堆栈分配的对象或删除的对象) 取消引用尚未被明确初始化的指针 执行指针算术,在数组的边界(上方或下方)之外产生结果。 将指针置于超出数组末尾的位置。 将指针转换为不兼容类型的对象 使用memcpy复制重叠的缓冲区 。 缓冲区溢出 读取或写入一个对象或数组的偏移量为负数,或超出该对象的大小(堆栈/堆溢出) 整数溢出 签名整数溢出 评估不是数学定义的表达式 左移值为负量(右移量为负数量为实现定义) 将值 ...
  • 警告:这是一个很长的解释,但希望它真的不仅解释了SFINAE的作用,而且还提供了什么时候和为什么使用它。 好的,为了解释这一点,我们可能需要备份和解释模板。 众所周知,Python使用通常称为鸭式打字的东西 - 例如,当您调用函数时,只要X提供函数使用的所有操作,就可以将对象X传递给该函数。 在C ++中,普通(非模板)函数需要指定参数的类型。 如果您定义了如下功能: int plus1(int x) { return x + 1; } 您只能将该函数应用于int 。 事实上,它以一种可能适用于其他类型( ...
  • 为什么他们的括号包含在变量i中? & 为什么删除[] p而不是变量p? p= new (nothrow) int [i]; 动态分配i元素的int数组。 delete []p; 删除动态分配的数组。 C ++中动态分配的基本规则是: 如果使用new来动态分配内存,请使用delete取消分配内存。 如果使用new []动态分配内存,请使用delete []取消分配。 另外,请注意您正在使用new运算符的nothrow版本,如果出现某些错误情况并且不抛出异常,它基本上返回null ,这允许C ++代码与 ...
  • 问题似乎在其他地方。 如果你需要教Java程序员如何编写一个简单的计算器,问题不在于语言,问题是对编程的基本理解。 我觉得学习编程的更糟糕的方法是编写没人使用的玩具。 根据我的说法,最好的方法是从简单但有用的工具开始,因为这会给程序员带来压力:事情实际上会被其他人使用; 它必须工作! 如果任务是管理的,那么让他写一个disk usage utility并告诉他你将使用它。 如果任务是科学的,让他写一个非线性方程求解器。 当然。 C ++是一门很难掌握的复杂语言(我甚至不是非常接近,我只知道两个人,我会考虑专 ...
  • Bjarne Stroustrup(C ++的发明者)编写的C ++编程语言 The C++ Programming Language Written by Bjarne Stroustrup (the inventor of C++)
  • 处理SIGSEGV等,可能允许保存状态并采取纠正措施。 先生32 (和其他人)是正确的,你不能简单地重新启动主线代码。 相反,你可以 longjmp() siglongjmp() ; 这允许重新开始主线。 此外,您必须非常小心才能调用async safe功能。 这非常棘手。 但是有些应用程序, 健康/安全 - 确保不会发生灾难性情况。 财务 - 可能导致资金损失的交易数据丢失。 控制系统 - 用于化学家的示例滴定软件。 诊断 - 可能会记录崩溃情况以改进未来的软件。 根据周杰伦 调用exit()可能不太好, ...
  • 当您通过Python解释器运行脚本(或从另一个脚本导入该脚本)时, 它实际上会从头到尾执行所有代码 - 从这个意义上说, Python脚本没有“入口点” 。 所以为了解决这个问题,Python自动创建一个__name__变量,并在你自己运行一个脚本时(而不是其他的脚本导入)创建一个__name__变量,并用值"__main__"填充它。 这就是为什么你会看到许多脚本,如: def foo(): print "Hello!" if __name__ == "__main__": foo() ...
  • 如果你从来没有正确学过C ++(你说你学会了“很糟糕”),重新开始。 忘记关于Java的所有内容,因为尝试在C ++中使用Java习语和技术只是错误和内存泄漏以及非常低效的代码的秘诀。 语言之间的差异相当大。 因此,从头开始写一本好书教C ++。 If you never properly learned C++ (you say you learned it "badly"), start over. Forget everything about Java, because trying to use ...
  • 我发现java项目的结构相当不错。 我这样做(root是根目录) root / include / foo / bar / baz.hpp成为 namespace foo { namespace bar { // declare/define the stuff (classes, functions) here } } // foo::bar 在代码中。 我保留了源代码 root / src / foo / bar / baz.cpp 。 如果我有一些没有暴露在外面的东西,我把它放入一个det ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)