2017-09-29 11 views
0

私は私が管理し、この目標にApplicationクラスを書きましたように、複数の活動にサービスをバインドする:バインドサービス

public class BluetoothController extends Application { 
    private static BluetoothController mInstance; 
    private ClientBluetoothService mService; 
    protected boolean mBound = false; 

    public static synchronized BluetoothController getInstance() { 
     return mInstance; 
    } 

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

    public void startService(){ 
     //start your service 
     Intent intent = new Intent(this, ClientBluetoothService.class); 
     bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 
    } 
    public void stopService(){ 
     //stop service 
     if (mBound) { 
      unbindService(mConnection); 
      mBound = false; 
     } 
    } 

    public ClientBluetoothService getService(){ 
     return mService; 
    } 

    public boolean isBound() { 
     return mBound; 
    } 

    private ServiceConnection mConnection = new ServiceConnection() { 

     @Override 
     public void onServiceConnected(ComponentName className, IBinder service) { 

      ClientBluetoothService.LocalBinder binder = (ClientBluetoothService.LocalBinder) service; 
      mService = binder.getSerivce(); 
      mBound = true; 
     } 

     @Override 
     public void onServiceDisconnected(ComponentName arg0) { 
      mBound = false; 
     } 
    }; 
} 

そして、私は、たとえば使用している活動で、このクラスにアクセスするには: java.lang.NullPointerExceptionが::nullのオブジェクト参照の上に「()、ボイドcom.gmail.krakow.michalt.myecg.BluetoothController.startService」の仮想メソッドを呼び出そうと

BluetoothController.getInstance().startService(); 

は、しかし、私はエラーを持っています。 どうすれば解決できますか?

+0

さらに、これを行う必要は全くありません。複数のアクティビティをサービスにバインドする場合は、それぞれのサービスでbindServiceを呼び出します。または、アクティビティの共通基本クラスに入れます。それはアプリケーションに入れる意味がありません –

+0

'BluetoothController'の使い方、 'isBound()'の後に 'getService()'をどのように使いたいのですか? – samosaris

+0

それは良い考えではありませんでした。 @GabeSechanの指示に従うとうまくいきます。 – michalt38

答えて

-1
public static synchronized BluetoothController getInstance() { 
    return mInstance = new BluetoothController(); 
} 
+0

Obviosulyあなたは 'Application'、' Service'、 'Activity'のようなクラスで自分自身で' new operator'を呼び出すべきではありません – Selvin

関連する問題