Java 使用openFileOutput时是否正确使用内部类中的上下文?

Java 使用openFileOutput时是否正确使用内部类中的上下文?,java,android,inner-classes,android-context,Java,Android,Inner Classes,Android Context,我正在尝试修改Android BluetoothChat示例,以便使用类中的openFileOutput将InputStream保存到文件中。使用Environment.getExternalStorageDirectory并使用filewriter保存到SD卡时没有问题,但是使用带有MODE_PRIVATE的openFileOutput方法会返回nullPointerException,如其他几个问题/答案中所述。我一辈子都想不出获得正确上下文的正确方法 private class Co

我正在尝试修改Android BluetoothChat示例,以便使用类中的openFileOutput将InputStream保存到文件中。使用Environment.getExternalStorageDirectory并使用filewriter保存到SD卡时没有问题,但是使用带有MODE_PRIVATE的openFileOutput方法会返回nullPointerException,如其他几个问题/答案中所述。我一辈子都想不出获得正确上下文的正确方法

   private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private Context mContext;

        public ConnectedThread(BluetoothSocket socket) {
            Log.d(TAG, "create ConnectedThread");
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            byte[] buffer = new byte[1024];
            int bytes;

            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);
                    // Save to file
                    String FILENAME = "chat.txt";

                    FileOutputStream fos = mContext.openFileOutput(FILENAME, Context.MODE_PRIVATE);
                    fos.write(bytes);
                    fos.close();
                    // Send the obtained bytes to the UI Activity
                    mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }
            }
        }

现在McContext是空的。你没有给它分配任何东西。您可以更改构造函数签名以将其传入:

public ConnectedThread(Context context, BluetoothSocket socket) {
    this.mContext = context;
    ...
}

如果你真的在遵循这个例子,你可以在
BluetoothChatService
中做同样的事情。。。请注意,它们不会对传入的上下文执行任何操作。将该上下文存储在一个字段中,并且
ConnectedThread

也可以访问该上下文,以这种方式保留对上下文的引用可能会泄漏。这件事至少需要一个析构函数。我认为更好的方法是获取对应用程序上下文的引用,因为这里没有与显示相关的代码。