服务未绑定活动,空指针异常

时间:2014-06-05 07:56:21

标签: android android-service

这是我的代码。

    public class ScheduleClient {

    // The hook into our service
    private ScheduleService mBoundService;
    // The context to start the service in
    private Context mContext;
    // A flag if we are connected to the service or not
    private boolean mIsBound;

    public ScheduleClient(Context context) {
        mContext = context;
    }


    public void doBindService() {
        // Establish a connection with our service
        mContext.bindService(new Intent(mContext, ScheduleService.class),
                mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }


    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;
        }
    };

    /**
     * Tell our service to set an alarm for the given date
     * 
     * @param c
     *            a date to set the notification for
     */
    public void setAlarmForNotification(Calendar c) {
        if (mBoundService != null)
            mBoundService.setAlarm(c);
        else
            Log.e("@ScheduleClient", "mBoundService is null");
    }

    public void cancelAlarmForNotification() {
        mBoundService.cancelAlarm();
    }

    /**
     * When you have finished with the service call this method to stop it
     * releasing your connection and resources
     */
    public void doUnbindService() {
        if (mIsBound) {
            // Detach our existing connection.
            mContext.unbindService(mConnection);
            mIsBound = false;
        }
    }
}

清单文件

<service android:name="com.mobtecnica.inreez.reminder.ScheduleService" >
    </service>

此处mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);始终返回false。 所以mBoundService变为空。这意味着该服务没有绑定。我该如何解决这个问题。我正在尝试在我的应用程序中设置提醒。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

那么,绑定服务并因此初始化mBoundService的方法是doBindService()。从未调用过。看看here,有一个非常好的例子可以满足您的所有需求。