Android 绑定服务 onStart 不起作用



我有一个服务(绑定(,我正在尝试从我的 MainActivity 开始.java。以下是我的主要活动代码:

public class MainActivity extends AppCompatActivity {
Handler m_handler;
Runnable m_handlerTask ;
private static ServiceConnection sConnection;
static boolean  serviceBound = false;
@Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, DataDownloaderService.class);
bindService(intent, sConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.NoActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
if (!Global.isMyServiceRunning(DataDownloaderService.class, this)) {
sConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
DataDownloaderService.LocalBinder binder = (DataDownloaderService.LocalBinder) service;
Global.dService = binder.getService();
serviceBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
serviceBound = false;
}
};
}
}
catch(Exception ex ){
String p="";
}
}
@Override
protected void onResume(){
super.onResume();
m_handler = new Handler();
m_handlerTask = new Runnable()
{
@Override
public void run() {
RefreshNowPlaying();
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();           
}
}

void RefreshNowPlaying(){
//Do something            
}        
}

服务代码如下所示:

public class DataDownloaderService extends Service {
private final IBinder dBinder = new LocalBinder();
public class LocalBinder extends Binder {
DataDownloaderService getService() {
// Return this instance of LocalService so clients can call public methods
return DataDownloaderService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return dBinder;
}
@Override
public void onCreate(){
}
@Override
public void onStart(Intent intent, int startid){
super.onStart(intent,startid);
Global.DataDownloaderServiceStatus = "STARTED";
}
@Override
public void onDestroy(){
Global.DataDownloaderServiceStatus = "STOPPED";
super.onDestroy();
}
}

我还在应用程序元素下.xml将该服务添加到AndroidManifest中。但是,我看到服务的onStart从未被触发,或者从未调用过MainActivity中的OveroveronServiceConnected。我是Anrdoid开发和Java的新手。有人可以给我一些指示吗?我注意到该服务的onCreate通过放置断点而受到打击,但不是onStart。

只有当服务通过 context.startService(( 启动时,才会调用onStart(),请参阅此处。

相关内容

  • 没有找到相关文章

最新更新