BluetoothChatService 클래스 내에서 openFileOutput을 사용하여 InputStream을 파일에 저장하기 위해 Android BluetoothChat 예제를 조정하려고합니다. Environment.getExternalStorageDirectory를 사용하고 filewriter를 사용하여 sdcard에 저장할 때 문제는 없지만 MODE_PRIVATE와 함께 openFileOutput 메소드를 사용하면 몇 가지 다른 질문/답변에서 언급 한 것처럼 nullPointerException을 반환합니다. 나는 내 삶에 대해 정확한 문맥을 얻는 정확한 방법을 찾아 낼 수 없다.openFileOutput을 사용할 때 내부 클래스에서 컨텍스트를 올바르게 사용합니까?
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;
}
}
}
이런 식으로 컨텍스트에 대한 참조를 유지하면 누출 될 수 있습니다. –
이 것은 적어도 소멸자가 필요합니다. 디스플레이 관련 코드가 없으므로 애플리케이션 컨텍스트에 대한 참조를 얻는 것이 더 나은 접근 방법이라고 생각합니다. –