2013-08-25 25 views
0

我有以下代码:为什么我的有界的android服务是空的?

public void refreshWidget() { 
    doBindService(); 
    mBoundService.loadState(); 
    doUnbindService(); 
} 


private static ServiceConnection mAppWidgetServiceConnection = new ServiceConnection() { 

    @Override 
    public void onServiceConnected(ComponentName className, IBinder service) { 
     // This is called when the connection with the service has been 
     // established, giving us the service object we can use to 
     // interact with the service. Because we have bound to a explicit 
     // service that we know is running in our own process, we can 
     // cast its IBinder to a concrete class and directly access it. 
     mBoundService = ((AppWidgetService.LocalBinder) service) 
       .getService(); 
    } 

    @Override 
    public void onServiceDisconnected(ComponentName className) { 
     // This is called when the connection with the service has been 
     // unexpectedly disconnected -- that is, its process crashed. 
     // Because it is running in our same process, we should never 
     // see this happen. 
     mBoundService = null; 
    } 
}; 

static void doBindService() { 
    // Establish a connection with the service. We use an explicit 
    // class name because we want a specific service implementation that 
    // we know will be running in our own process (and thus won't be 
    // supporting component replacement by other applications). 
    if (!mIsBound) { 
     // mContext.startService(new Intent(mContext, 
     // AppWidgetService.class)); 
     mContext.bindService(new Intent(mContext, 
       AppWidgetService.class), 
       mAppWidgetServiceConnection, Context.BIND_AUTO_CREATE); 
     mIsBound = true; 
    } 
} 

怎么能在这一行mBoundService.loadState();mBoundService==null

我错过了什么?

回答

0

你不能叫mBoundService.loadState();doBindService();立即因为服务没有限制在这个时候。

呼叫mBoundService.loadState();回调后onServiceConnected

+0

在''onServiceConnected我尝试调用'mBoundService.startService(新意图(AppWidgetService.APPWIDGET_ACTION_CMD_REFRESH))'。如何执行服务的'public void onStart(Intent aIntent,int aStartId)'?只有当我调用'mBoundService.onStart(新的意图(AppWidgetService.APPWIDGET_ACTION_CMD_REFRESH),-1);' –