java - 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();
}
}
我还在 Application 元素下的 AndroidManifest.xml 中添加了该服务。但是,我看到该服务的 onStart 从未被触发,或者 MainActivity 中的覆盖 onServiceConnected 从未被调用。我是 Anrdoid 开发和 Java 的新手。有人可以给我一些指示吗?我注意到服务的 onCreate 通过放置断点而不是 onStart 受到打击。
解决方案
onStart()
只有通过 context.startService() 启动服务时才会调用,请参见此处。
推荐阅读
- node.js - async/await 和 http 客户端请求的问题
- node.js - 在 AppEngine Node.js 标准环境中稳定快速会话
- matlab - matlab代码生成重采样:项数N必须是常数
- angular - 如何在剑道网格中执行服务器端过滤以获取角度
- xamarin.android - 根据条件更改工具栏
- javascript - 负 z-index 在模态中不起作用
- ruby-on-rails - 升级到 macOS Mojave,现在在 Rails 控制台中出现错误
- hyperledger-fabric - 错误:2 未知:访问被拒绝:频道 [composerchannel] creator org
- angular - 需要在 columnsMenuTab ag 网格中进行修改
- c++ - 如何转换真实路径CString c ++