2012-08-03 4 views
0

서비스에 블루투스 브로드 캐스트 리시버 메소드를 호출 할 수 없습니다내가이 서비스 클래스가

public class BluetoothService extends Service { 

    private static Activity mActivity; 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     IntentFilter intentFilter = new IntentFilter(); 
     intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); 
     this.registerReceiver(bluetoothReceiver, intentFilter);  
    } 

    @Override 
    public void onDestroy() { 
     if (bluetoothReceiver != null) { 
      this.unregisterReceiver(bluetoothReceiver); 
     }  
    } 

    @Override 
    public void onStart(Intent intent, int startid) { 
      // 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) {   
     return START_STICKY; 
    } 

    public static BroadcastReceiver bluetoothReceiver = new BroadcastReceiver(){ 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { 
       final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); 
       TextView tvStatus = (TextView) mActivity.findViewById(R.id.tvtatus); 
       Messaging.appendMessage(tvStatus, Bluetooth.getDeviceState(state)); 
       if (Bluetooth.isBluetoothEnabled()) { 
        Messaging.appendMessage(tvStatus, Bluetooth.showMessage()); 
       }    
      } 
     } 
    }; 
} 

그리고 내 활동 수업을, 나는이 있습니다

public class MainActivity extends Activity { 

    private TextView tvStatus; 
    private Intent intentBluetooth; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     tvStatus = (TextView)findViewById(R.id.tvtatus); 

     intentBluetooth = new Intent(this, BluetoothService.class); 
     startService(intentBluetooth); 
    } 
} 

브로드 캐스트 리시버 방법 (bluetoothReceiver) Service 클래스에서 호출되지 않습니다. 나는 이유를 모른다. 무엇보다도 IntentFilter와 BroadcastReceiver 코드가 하나의 액티비티에 있으면 작동하지만 - [별도의] 서비스에는 없습니다. 나는 혼란 스럽다.

내의 AndroidManifest.xml은 다음과 같습니다

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
     package="com.onegoal.androidexample" 
     android:versionCode="1" 
     android:versionName="1.0.0" 
     android:installLocation="auto" 
     android:hardwareAccelerated="true"> 

     <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="15" /> 

     <uses-permission android:name="android.permission.BLUETOOTH" /> 
     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 
     <uses-feature android:name="android.hardware.bluetooth" android:required="false" /> 

     <application 
      android:icon="@drawable/ic_launcher" 
      android:label="@string/app_name" 
      android:theme="@style/AppTheme" 
      android:debuggable="true" > 
      <activity 
       android:name=".MainActivity" 
       android:label="@string/app_name" 
       android:theme="@android:style/Theme.NoTitleBar" > 
       <intent-filter> 
        <action android:name="android.intent.action.MAIN" /> 
        <category android:name="android.intent.category.LAUNCHER" /> 
       </intent-filter> 
      </activity> 
      <service android:name=".BluetoothService"> 
      </service> 
     </application> 
    </manifest> 

은 내가 최선을하지 않을 수 있습니다 뭘하는지 너무 안드로이드에 새로운 해요. 누군가 나를 도울 수 있기를 바랍니다.

+0

당신이 AndroidManifest.xml에 블루투스 권한을 부여했다? – Lucifer

+0

예, AndroidManifest.xml에 다음 권한이 있습니다. ChuongPham

+0

Manifest의 수신기와 @ 루시퍼 (Lusifer)는 허가를 받았다고 말했습니까 ?? 심지어 내가 할 수 있다고 생각 TextView tvStatus = (TextView) mActivity.findViewById (R.id.tvtatus); UR 수신기에 ..? – AAnkit

답변

4

어쩌면 수신기가 정적 인이라는 사실이 원인 일 수 있습니다.

BroadcastReceiver은 절대로 정적이어서는 안됩니다. 그것은 많은 문제를 일으킬 수 있습니다.

코드에서 다른 실제적으로 잘못된 디자인 문제 - 서비스 내부의 활동에 대한 참조를 유지하고 뷰를 수정하여 사용하는 것은 실제로 잘못된 행동입니다. 메모리 리크를 쉽게 일으킬 수 있습니다. ServiceActivity 사이에서 통신하는 이유는 android의 Messanger을 구현하거나 BroadcastReceiver을 통해 브로드 캐스트를 보내는 것입니다.

내 조언을 듣는다면 - 수신기를 정적으로 만들지 않아도됩니다. (내 안에 정적 인스턴스를 사용하고 있기 때문에 정적으로 만 만들었을 것입니다) 저는 귀엽습니다. 확실히 그것은 당신이 약 Messanger 여기에 읽을 수있는 문제

해결됩니다 : 당신은 그물에 예문을 많이 찾을 수 있습니다 http://developer.android.com/reference/android/os/Messenger.html

확인합니다. 서비스에서 활동 방송 업데이트

예 :

public class MyService extends Service { 

@Override 
public IBinder onBind(Intent arg0) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public void onCreate() { 
    super.onCreate(); 

    IntentFilter intentFilter = new IntentFilter(); 
    intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); 
    this.registerReceiver(bluetoothReceiver, intentFilter); 
} 

@Override 
public void onDestroy() { 
    if (bluetoothReceiver != null) { 
     this.unregisterReceiver(bluetoothReceiver); 
    } 
    super.onDestroy(); 
} 

public BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { 
      final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); 
      updateUIWithNewState(state); 
     } 
    } 
}; 

protected void updateUIWithNewState(int state) { 
    Intent intent = new Intent("serviceUpdateReceivedAction"); 
    intent.putExtra("state", state); 
    sendBroadcast(intent); 
} 

} 

과 그 활동의 :

public class MyActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    Intent intent = new Intent(this, MyService.class); 
    startService(intent); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 

    registerReceiver(mServiceUpdatesReceiver, new IntentFilter("serviceUpdateReceivedAction")); 
} 

@Override 
protected void onPause() { 
    unregisterReceiver(mServiceUpdatesReceiver); 
    super.onPause(); 
} 

private BroadcastReceiver mServiceUpdatesReceiver = new BroadcastReceiver() { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     int state = intent.getIntExtra("state", -1); 
     // do what ever you want in the UI according to the state 
    } 
}; 
} 
+0

수신기를 비 정적으로 만들면 아무런 차이가 없습니다. 이전에 Messenger 클래스를 본 적이 있지만이 클래스가 BluetoothAdapter.EXTRA_STATE와 같은 의도로 BroadcastReceiver에서받은 점진적 업데이트 메시지를 보낼 수있는 방법을 찾을 수 없습니다. – ChuongPham

+0

@Chuong : 가능한지 아닌지에 대해 논쟁하기 시작하고 싶지 않습니다. 당신의 수신기가하고있는 모든 것이 설정 텍스트 인 textView라면 왜 서비스가 필요할까요? 그것은 활동 내부 수신기를 구현하기위한 고전적인 이유입니다. –

+0

나는 당신과 논쟁하지 않습니다. 나는 Messenger 클래스를 사용할 방법을 찾을 수 없다는 것을 말하고있다. 그게 다야.그것이 오해를 없애기를 희망한다. – ChuongPham

관련 문제