마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

버튼을 눌렀을때 기본예제블루투스채트 화면으로 구성되는 앱입니다.★★★

+1 추천

버튼을 누르,면 블루투스 앱으로 연결됩니다.

블루투스 채트 자바파일쪽으로 넘어가는데 


기본 블루투스채트 예제랑 같은 코드 구성입니다.

(8000자 이상 입력이 불가능해서 ㅠㅠ 기본블루투스 채트 예제의 bluetooth chat 이 자바파일입니다)

이 자바 소스외에도 디바이스 리스트나 블루투스 채트서비스라는 자바파일도 있지만 일단 이 소스가 메인이고 여기서 다 구성되는것으로 알고있기에 이 소스만 올립니다. 일단 이 소스로 구성했을때 원래 정상단독 구동되는 앱이었구요 메인액티비티에서 이 화면으로 인텐트되는 형식입니다.

문제는

저 버튼을 누르면 블루투스 연결하겠습니까 나오구요

여기서 "예"를 누르면

이렇게 꺼져버립니다.

원래 단독 구동되던 앱이고 소스상에는 아마 문제가 없을텐데

맨처음 버튼을 누르고 구동되는것에서 문제가 있는것 같은데

그게 뭔지 도무지 감이 안잡힙니다.

안드로이드 아직 입문하는 개발자이구

잘 몰라서 질문드리니 ㅠㅠ

잘부탁드립니다.

조금 급하게 구성해야되서 ㅠㅠㅠㅠ

진짜 잘부탁드립니다 감사합니다 ㅠㅠ

블루투스빠도리 (600 포인트) 님이 2014년 7월 20일 질문
블루투스빠도리님이 2014년 7월 20일 수정

8개의 답변

0 추천
@SuppressLint("NewApi") public class BluetoothChat extends Activity {
   
    private static final String TAG = "BluetoothChat";
    private static final boolean D = true;
 
   
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
 
  
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
 
  
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
    private static final int REQUEST_ENABLE_BT = 3;
 
   
    private ListView mConversationView;
    private EditText mOutEditText;
    private Button mSendButton;
 
   
    private String mConnectedDeviceName = null;
   
    private ArrayAdapter<String> mConversationArrayAdapter;
  
    private StringBuffer mOutStringBuffer;
   
    private BluetoothAdapter mBluetoothAdapter = null;
  
    private BluetoothChatService mChatService = null;
 
    Button button;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(D) Log.e(TAG, "+++ ON CREATE +++");
 
       
        setContentView(R.layout.second_main);
 
       
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
 
        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        
      
    
블루투스빠도리 (600 포인트) 님이 2014년 7월 20일 답변
블루투스빠도리님이 2014년 7월 20일 reshown
0 추천
  //fornt move
        button = (Button)findViewById(R.id.button2);
        button.setOnClickListener(new Button.OnClickListener() {
 
@Override
public void onClick(View v) {
sendMessage("1");
}
});
        
        // back move
        button = (Button)findViewById(R.id.button8);
        button.setOnClickListener(new Button.OnClickListener() {
 
@Override
public void onClick(View v) {
sendMessage("2");
}
});
        
        // left move
        button = (Button)findViewById(R.id.button4);
        button.setOnClickListener(new Button.OnClickListener() {
 
@Override
public void onClick(View v) {
sendMessage("3");
}
});
        
        // right move
        button = (Button)findViewById(R.id.button6);
        button.setOnClickListener(new Button.OnClickListener() {
 
@Override
public void onClick(View v) {
sendMessage("4");
}
});
        
        // move stop
        button = (Button)findViewById(R.id.button5);
        button.setOnClickListener(new Button.OnClickListener() {
 
@Override
public void onClick(View v) {
sendMessage("5");
}
});
        button = (Button)findViewById(R.id.button9);
        button.setOnClickListener(new Button.OnClickListener() {
 
@Override
public void onClick(View v) {
sendMessage("11");
}
});
        button = (Button)findViewById(R.id.button10);
        button.setOnClickListener(new Button.OnClickListener() {
 
@Override
public void onClick(View v) {
sendMessage("12");
}
});
        button = (Button)findViewById(R.id.button11);
        button.setOnClickListener(new Button.OnClickListener() {
 
@Override
public void onClick(View v) {
sendMessage("13");
}
});
       
        button = (Button)findViewById(R.id.button12);
        button.setOnClickListener(new Button.OnClickListener() {
 
@Override
public void onClick(View v) {
sendMessage("14");
}
});
        
        
        
    }
 
  
블루투스빠도리 (600 포인트) 님이 2014년 7월 20일 답변
블루투스빠도리님이 2014년 7월 20일 reshown
0 추천
@Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");
 
        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
        } else {
            if (mChatService == null) setupChat();
        }
    }
 
    @Override
    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");
 
        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
              // Start the Bluetooth chat services
              mChatService.start();
            }
        }
    }
 
    private void setupChat() {
        Log.d(TAG, "setupChat()");
 
        // Initialize the array adapter for the conversation thread
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        mConversationView = (ListView) findViewById(R.id.in);
        mConversationView.setAdapter(mConversationArrayAdapter);
 
        // Initialize the compose field with a listener for the return key
        mOutEditText = (EditText) findViewById(R.id.edit_text_out);
        mOutEditText.setOnEditorActionListener(mWriteListener);
 
        // Initialize the send button with a listener that for click events
        mSendButton = (Button) findViewById(R.id.button_send);
        mSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Send a message using content of the edit text widget
                TextView view = (TextView) findViewById(R.id.edit_text_out);
                String message = view.getText().toString();
                sendMessage(message);
            }
        });
 
        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new BluetoothChatService(this, mHandler);
 
        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }
 
    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }
 
    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mChatService != null) mChatService.stop();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
    }
 
    private void ensureDiscoverable() {
        if(D) Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }
 
블루투스빠도리 (600 포인트) 님이 2014년 7월 20일 답변
0 추천
    private void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }
 
        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);
 
            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
            mOutEditText.setText(mOutStringBuffer);
        }
    }
 
    // The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener mWriteListener =
        new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                String message = view.getText().toString();
                sendMessage(message);
            }
            if(D) Log.i(TAG, "END onEditorAction");
            return true;
        }
    };
 
    private final void setStatus(int resId) {
        final ActionBar actionBar = getActionBar();
        actionBar.setSubtitle(resId);
    }
 
    private final void setStatus(CharSequence subTitle) {
        final ActionBar actionBar = getActionBar();
        actionBar.setSubtitle(subTitle);
    }
 
    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothChatService.STATE_CONNECTED:
                    setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
                    mConversationArrayAdapter.clear();
                    break;
                case BluetoothChatService.STATE_CONNECTING:
                    setStatus(R.string.title_connecting);
                    break;
                case BluetoothChatService.STATE_LISTEN:
                case BluetoothChatService.STATE_NONE:
                    setStatus(R.string.title_not_connected);
                    break;
                }
                break;
            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                String writeMessage = new String(writeBuf);
                mConversationArrayAdapter.add("Me:  " + writeMessage);
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
 
블루투스빠도리 (600 포인트) 님이 2014년 7월 20일 답변
0 추천
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE_SECURE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data, true);
            }
            break;
        case REQUEST_CONNECT_DEVICE_INSECURE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data, false);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
                setupChat();
            } else {
                // User did not enable Bluetooth or an error occurred
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
 
    private void connectDevice(Intent data, boolean secure) {
        // Get the device MAC address
        String address = data.getExtras()
            .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        // Get the BluetoothDevice object
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        // Attempt to connect to the device
        mChatService.connect(device, secure);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent serverIntent = null;
        switch (item.getItemId()) {
        case R.id.secure_connect_scan:
            // Launch the DeviceListActivity to see devices and do scan
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
            return true;
        case R.id.insecure_connect_scan:
            // Launch the DeviceListActivity to see devices and do scan
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
            return true;
        case R.id.discoverable:
            // Ensure this device is discoverable by others
            ensureDiscoverable();
            return true;
        }
        return false;
    }
 
}
 
블루투스빠도리 (600 포인트) 님이 2014년 7월 20일 답변
0 추천
맨 밑부터 역순으로

코드 구성입니다 ㅠㅠ

잘부탁드립니다 정말 급해서 ㅠㅠㅠ

부탁드립니다
블루투스빠도리 (600 포인트) 님이 2014년 7월 20일 답변
0 추천
이건 뭐...기다려도 답변이 힘듭니다.

로그와 로그에 관련된 소스코드를 올려주세요. 블루투스 챗 예제를 봤으니 어느정도는 답변해드릴수 있습니다.
인연 (31,880 포인트) 님이 2014년 7월 21일 답변
쪽지 보냈습니다 ㅠㅠ
확인해보시고 연락주세요 감사합니다
전화는 힘든 상황이라... 우선 추측되는 문제점은 권한 문제가 아닐까 싶습니다. 다른 문제가 있을수도 있으니 로그를 첨부하여 올려주세요.
올렸습니다 한번 봐주시고 답변주세요 감사합니다 ㅠㅠ
정말 급한상황이라 ㅠㅠ 감사하고 죄송합니다  ㅠㅠ
a11233324dfsdfsd
0 추천

 

 

로그캣 내역입니다 ㅠㅠ 보시고 답해주시면 감사하겠습니다 

 

07-26 11:47:57.420: E/BluetoothChat(30673): +++ ON CREATE +++
07-26 11:47:57.490: E/BluetoothChat(30673): ++ ON START ++
07-26 11:47:57.490: E/BluetoothChat(30673): + ON RESUME +
07-26 11:47:57.640: E/AndroidRuntime(30673): FATAL EXCEPTION: main
07-26 11:47:57.640: E/AndroidRuntime(30673): Process: gi.si, PID: 30673
07-26 11:47:57.640: E/AndroidRuntime(30673): java.lang.NullPointerException
07-26 11:47:57.640: E/AndroidRuntime(30673): 	at gi.si.BluetoothChat.setStatus(BluetoothChat.java:322)
07-26 11:47:57.640: E/AndroidRuntime(30673): 	at gi.si.BluetoothChat.access$4(BluetoothChat.java:320)
07-26 11:47:57.640: E/AndroidRuntime(30673): 	at gi.si.BluetoothChat$2.handleMessage(BluetoothChat.java:347)
07-26 11:47:57.640: E/AndroidRuntime(30673): 	at android.os.Handler.dispatchMessage(Handler.java:102)
07-26 11:47:57.640: E/AndroidRuntime(30673): 	at android.os.Looper.loop(Looper.java:136)
07-26 11:47:57.640: E/AndroidRuntime(30673): 	at android.app.ActivityThread.main(ActivityThread.java:5118)
07-26 11:47:57.640: E/AndroidRuntime(30673): 	at java.lang.reflect.Method.invokeNative(Native Method)
07-26 11:47:57.640: E/AndroidRuntime(30673): 	at java.lang.reflect.Method.invoke(Method.java:515)
07-26 11:47:57.640: E/AndroidRuntime(30673): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
07-26 11:47:57.640: E/AndroidRuntime(30673): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
07-26 11:47:57.640: E/AndroidRuntime(30673): 	at dalvik.system.NativeStart.main(Native Method)

 

블루투스빠도리 (600 포인트) 님이 2014년 7월 26일 답변
블루투스빠도리님이 2014년 7월 26일 수정
setStatus 에서 널포인터 에러가 발생하네요.. setStatus 메소드 안에 보면 handler로 통신을 하는 부분이 있습니다. 그 부분에서 아마 에러가 발생했을 것으로 생각됩니다.
BluetoothChat.java:322
봐보세요
BluetoothChat.java 에 322번째줄에 널포인터익셉션이떳네요.
...