我创建了一个服务并启动它,但onCreate()永远不会被调用。 这是我的TestService的一部分:
public class TestService extends Service {
private static boolean isRunning = false;
@Override
public void onCreate() {
super.onCreate();
isRunning = true;
}
...
和我的活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this,TestService.class));
}
最后我的清单:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".TestService"></service>
</application>
调用startService但是TestService的onCreate中的断点永远不会触发。在startService
之后,isRunning仍然是false答案 0 :(得分:0)
从我看到的一切看起来都很好,onCreate()
总是被调用(根据life cycle)。我只能想到两件事:
您的活动未被调用或遇到异常或
protected void onCreate(...)
(protected
?→更改为public
)
中您服务的路径
.
错误
<service android:name=".TestService"></service>
检查TestService
课程的包裹名称。
答案 1 :(得分:0)
您必须在活动开始时将活动与服务绑定。要实现此目的,您的服务必须包含活动将使用的活页夹。 有关详细信息,请查看Android Dev Docs
<强>服务强>
public class LocalService extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
// Random number generator
private final Random mGenerator = new Random();
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/** method for clients */
public int getRandomNumber() {
return mGenerator.nextInt(100);
}
}
<强>活动强>
public class BindingActivity extends Activity {
LocalService mService;
boolean mBound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}