我的应用程序将其信息存储在其服务上,并在onCreate()中绑定它以验证加载信息的服务状态是什么。我虽然它会使改变方向变得容易,因为他们将从重新创建的服务中恢复他的状态。但我的问题是,当调用onDestroy时,它会调用unbindService,但是在onServiceDisconnect之前调用onCreate会导致一些问题。以下是我的一些方法:
活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyService.log("Activity onCreate()");
setContentView(R.layout.activity_layout);
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
drawerlayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerlayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.LEFT);
// activity sendo criada pela primeira vez e não por mudança de
// orientação
registerReceivers();
// cancelaNotificacao(R.drawable.ic_launcher);
Intent it = new Intent(this, MyService.class);
if (!MyService.RUNNING) {
startService(it);
}
if (!bindService(it, this, 0)) {
mensagemErro("Erro!",
"Não foi possível conectar ao service. Fechando app.");
finish();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceivers();
unbindService(this);
}
@Override
public void onServiceConnected(ComponentName name, IBinder binderservice) {
MyService.log("Activity onServiceConnected");
LocalBinder binder = (LocalBinder) binderservice;
this.service = binder.getService();
carregaRadio();
if (MyService.bot != null && MyService.bot.isConnected()) {
carregaChatdoService();
selectTab(TITLE_TAB_CHAT);
} else {
carregaLogin();
selectTab(TITLE_TAB_RADIO);
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
在服务上:
public class LocalBinder extends Binder {
public MyService getService() {
// Return this instance of LocalService so clients can call public
// methods
return MyService.this;
}
}
@Override
public IBinder onBind(Intent arg0) {
log("Service Bind.");
BOUND = true;
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
log("Service Unbind.");
BOUND = false;
boolean stopserviceflag = true;
// Se nem o bot do irc e nem o player estao ativos, o service pode parar
// tambem
if (bot != null && bot.isConnected()) {
stopserviceflag = false;
}
if (playerStarted) {
stopserviceflag = false;
}
if (stopserviceflag) {
log("Service Stop.");
stopSelf();
}
return super.onUnbind(intent);
}
我想如果我的onServiceDisconnected在onCreate之前调用它会起作用,但真诚地不知道。
欢迎任何帮助。
答案 0 :(得分:0)
将服务绑定在Activity
中的onStart
unbind the service
和onStop
。这将解决您在方向更改方面的问题。
@Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, YourService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service if already bound .
// mBound will be true if service connection is established when onServiceConnected is called
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
这将确保service
仅bound
Activity
Activity
{{1}}位于前台(对用户可见且互动)。