Android 如何通过 Intent 在 Activity 之间传递输入流?

How to pass Input Stream between Activities via Intent in Android?

我有一个 InputStream 对象

InputStream _fileInput;

我想发送给另一个activity,比方说:

Intent intent = new Intent(MainActivity.this, ChildActivity.class);

我该怎么做?

您不能通过 Intent 传递它,也不能作为 Extra(因为它不是 Parcelable)创建 public getter 方法在您的 MainActivity 中调用它 ChildActivity..

示例代码:

class MainActivity {

    private static InputStream mInputStream;

    @Override
    protected onCreate(...) {

        mInputStream = new InputStream(.....);

        Intent i = new Intent(MainActivity.this, ChildActivity.class);
        startActivity(i);
    }

    public static getInStream() {
        return mInputStream;
    }
}


class ChildActivity {

    @Override
    protected onCreate(...) {
        InputStream theInputStream = MainActivity.getInStream();
    }

}

恕我直言,这不是最好的解决方案,但它仍然是某种东西,我认为我永远不会在活动之间传递类似 InputStream 的东西..

如果我可以问,你为什么需要这个?


解决方案 2 - 使用助手 class

您可以使用 Singleton Helper class 来轻松跟踪您需要的对象。

Class 助手将是:

class Helper {

    private static Helper mHelper;
    private InputStream mInputStream;

    private Helper(){

    }


    public static Helper getInstance() {
        if (mHelper != null)
            return mHelper;

        return new Helper();
    }


    public void setInputStreamer(InputStream is){
        mInputStream = is
    }

    public InputStream getInputStreamer(){
        return mInputStream
    }
}

然后在您的 MainActivity 调用中:

is = new InputStream(...);
Helper.getInstance().setInputStreamer(is);

Intent i = new Intent(MainActivity.this, ChildActivity.class);
startActivity(i);

并且在您的 ChildActivity 电话中:

InputStream theInputStream = Helper.getInstance().getInputStreamer();