2016-03-27 41 views
1

我遇到了一個奇怪的情況,我構建的對象在方法onHandleIntent中返回爲null,我不知道爲什麼或者如何解決它。IntentService在構建他之後不會保存我的對象

MyActivity

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

     // the bluetooth is mentioned in case you know a way to use it with out transfer it from the activity 
     BluetoothManager _bluetooth_manager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE); 
     myService = new MyService(new MyClass(_bluetooth_manager.getAdapter())); 

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

爲MyService

private MyClass X; 

public MyService(MyClass x) { 
    super("man"); //not so much in the movie... =p 
    X = x; 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
    // somehow X is null here after i set him in the constractor. any idea why? 
} 

如果有人可以修改我的標題我不知道我寫的好,清晰明白...謝謝!

回答

1

該構造函數將永遠不會被使用。您的IntentService在其他地方有一個零參數MyService構造函數—,它將是Android用來創建服務實例的構造函數。

+0

感謝您的快速回答。那麼如何將MyClass轉移到IntentService? – LamaTo

+0

我會自己回答,我會使用Intent.putExtra()它可能會工作。 – LamaTo

+1

@LamaTo:我不確定一個班級可以額外付費。使用額外的標誌來表明工作是什麼,而不是應該做這項工作的班級。該類是「IntentService」的實現細節。 – CommonsWare