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

안드로이드 정적/동적리시버에 대해서 질문좀..드립니다

0 추천

블루투스예제를 참고해서 처음부터 끝까지 짜보려고 하는데 막히는 부분이 많네요.;;

현재 블루투스 기기가 있는데, 핸드폰과 통신하고자 합니다.

일단 통신에 앞서 이 블루투스기기와 핸드폰이 연결되면, 제가 만든 앱을 실행시키고 싶습니다.

앱이 꺼진상태[실행x]에서 즉, 홈 대기 화면에서 이 블루투스 기기와 폰이 연결되면

앱을 띄우려고 했는데요. 동적리시버로 하려고 하니 onDestroy에 선언해놓은 리시버 해제unregisterReceiver 때문에

그런건지, 아무 반응이 없었습니다.

그래서 정적리시버로 변경해서 , androidmanifest에 아래와 같이 리시버를 등록하고, 

 <receiver android:name=".bReceiver"
            android:enabled="true"
            android:exported="false"
            >
            <intent-filter>
                <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
            </intent-filter>
 
bReceiver 클래스에서 감지해서, 앱을 실행시키려고 하는데요,
//브로드캐스트리시버
public class bReceiver extends BroadcastReceiver 
{

	BluetoothAdapter bAdapter;
	BluetoothDevice bDevice;
	@Override
	public void onReceive(Context context, Intent intent) 
	{
		String action  = intent.getAction();
		bAdapter = BluetoothAdapter.getDefaultAdapter();
		if(bAdapter.getState()==BluetoothAdapter.STATE_TURNING_ON
				||bAdapter.getState()==BluetoothAdapter.STATE_ON)
		{
////			//블루투스가 켜졌을 때 무조건..
			Log.d("bluettoh is on","popup");
			Intent intents = new Intent(context, MainActivity.class);
			intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			//새 task를 띄움
			context.startActivity(intents);
		}
		else if(bAdapter.getState()==BluetoothAdapter.STATE_TURNING_OFF)
		{
			Log.d("bluetooth is off","not popup");
			
			//이렇게 등록된 리시버는 등록한 액티비티가 사라지거나 하면 등록이 해제되는 단점이 있어 죽지 않는 서비스에서 등록합니다
		}
		else if(BluetoothDevice.ACTION_FOUND.equals(action))
		{
			Log.d("BluetoothDevice is found","not popup");
			bDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			if(bDevice.getBondState()!=BluetoothDevice.BOND_BONDED)
			{
				Log.d("not bonded","......");
			
			}
			
		}
		else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
		{
			bAdapter.cancelDiscovery();
			bDevice = bAdapter.getRemoteDevice(bDevice.getAddress());
			Log.d("............",bDevice.getName()+"/"+bDevice.getAddress());
		}
		else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action))
		{
			Log.d("gggggg","gggggg");
		}
		else if(bDevice.getBondState()==BluetoothDevice.BOND_NONE)//연결x
		{
			Log.d("11","11");
		}
		else if(bDevice.getBondState()==BluetoothDevice.BOND_BONDING)//연결시도중
		{
			Log.d("22","22");
		}
		else if(bDevice.getBondState()==BluetoothDevice.BOND_BONDED)//연결된 상태
		{
			Log.d("33","33");
			Intent intents = new Intent(context, MainActivity.class);
			intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			//새 task를 띄움
			context.startActivity(intents);
		}
	}
	

	
};

 

일단 이런식으로 소스를 짰습니다.
 
Intent intents = new Intent(context, MainActivity.class);
intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//새 task를 띄움
context.startActivity(intents);
가, 해당 조건에 맞는 경우 mainActivity화면을 띄워주는 것인데요,
이 블루투스 기기네임이 ABC라고 가정할 때, 이 앱과 연동하려면 기기네임과 기기주소가 필요하다는데..
어떤식으로 bond를 확인할 수있는지 궁금합니다.
앱내에서 굳이 검색해서 연결할 필요는 없구요, 앱 실행 전에 블루투스기능에서 ABC와 연결한 다음 연결을 감지해서
앱을 실행하고자 하는데..이게 잘 안되네요 제가 잘못 이해하고있는거같은데, 조언 좀 부탁드립니다..
 

 

anci (19,950 포인트) 님이 2014년 11월 11일 질문

1개의 답변

+1 추천
 
채택된 답변
기기가 연결됐다는 BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED 이런 걸로 해야합니다.

state change는 블루투스의 켜짐/꺼짐이에요
쎄미 (162,410 포인트) 님이 2014년 11월 11일 답변
anci님이 2014년 11월 11일 채택됨
답변 감사합니다.
그럼 매니페스트의 리시버에서  <action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED"/> 요렇게 추가해주면 되는건가요?
어제 로그인이 안되서  비로그인 회원"궁금"으로 올렸던게 저인데,
최종적으로 헤드셋을 연결하려고 합니다. 볼륨조절등을 앱에서 값을 받아서 구현해보려고하는데요, 예전엔 비슷한 예제로 헤드셋이 아니라 다른 기기로 값을 넘겨봤었는데 혹시 헤드셋과 많은 차이가 있는지요..?

현재 말씀해주신대로 블루투스 실시간 꺼짐/켜짐은 값을 잘 받아오는데 연결되는 것에 대해선 오류가 발생합니다.
else if(bDevice.getBondState()==BluetoothDevice.BOND_NONE)//연결x
이부분에서 Unable to start receiver com.example.bluetooth.bReceiver: java.lang.NullPointerException 오류가 발생합니다..
broadcast receiver로 안되면 intent filter 넣은 서비스를 미리 띄워놔야할 수도 있어요.
연결된 헤드셋 정보는 http://susemi99.kr/1348 에서 확인할 수 있고요
답변 감사합니다. 매니페스트 리시버 쪽에 추가한
 <action android:name="android.bluetooth.device.action.BOND_STATE_CHANGED"/>
요녀석이 (bDevice.getBondState()==BluetoothDevice.BOND_NONE)의 기능이 동작하는 인텐트 필터 아닌가요?
동적 리시버로 해보려고했는데, 앱이 destroy될 때 리시버를 해제하는 것때문에, 앱이 완전히 종료된상태에서 특정조건에 띄울수가 없는지라 정적리시버를 사용하는데 매니페스트에 뭘 추가해야 하는지 아직 헷갈립니다ㅠ 헤드셋을 핸드폰과 연결할 때 bond_bonded로 감지할 수는 없는지요?
bond는 아닐거예요. 이렇게 해보세요. http://www.masterqna.com/android/36199
매니페스트에 안되면 service를 띄워야 할 듯 싶네요
...