我正在尝试绑定服务,但onBind()
总是返回 false。
这是ServiceConnection
-
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with our service has been established,
// giving us the service object we can use to interact with our service.
mBoundService = ((ScheduleService.ServiceBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
}
};
这是呼吁bindService()
-
boolean test = getApplicationContext().bindService(new Intent(this, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
这是 Manifest 中服务的声明——
<service android:name=".Notifications.ScheduleService" android:enabled="true"/>
我已经阅读了有关该主题的先前问题,但找不到答案(尝试使用 Application 上下文切换 Activity 上下文,但没有帮助)。
我正在使用 Fragments 和 ActionBarSherlock,并且我的 Activity 扩展SlidingFragmentActivity
(这就是我使用应用程序上下文的原因,这没有帮助)。
编辑-这是我要启动的服务的代码-
public class ScheduleService extends Service {
/**
* Class for clients to access
*/
public class ServiceBinder extends Binder {
public ScheduleService getService() {
return ScheduleService.this;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("ScheduleService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly stopped, so return sticky.
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients. See
private final IBinder mBinder = new ServiceBinder();
/**
* Show an alarm for a certain date when the alarm is called it will pop up a notification
*/
public void setAlarm(Calendar c) {
// This starts a new thread to set the alarm
// You want to push off your tasks onto a new thread to free up the UI to carry on responding
new AlarmTask(this, c).run();
}
}
任何帮助将不胜感激 。谢谢。