重新绑定后台服务进程(Android)

时间:2012-05-08 08:01:39

标签: android service background

我一直在研究这个问题,但没有找到明确的答案。

功能性挑战是:

a)使用布局启动活动(确定)

b)按钮(标记为START),单击ist启动后台服务(OK)

c)可以关闭活动,后台服务必须继续运行(确定)

d)后台进程仍然存在,我可以在我的通知中看到它(OK)

e)活动从通知重新开始(OK)

f)活动必须连接到流程并获取其状态。只需检查服务是否正在运行,并将开始 - 停止 - 按钮的标签从(b)设置为STOP。

e)点击按钮将停止服务,这样就可以了。

以下是一些细节:

与我的服务LogoTimerService的连接在以下活动中完成:

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
        LogoTimerServiceBinder binder = (LogoTimerServiceBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        mBound = false;
    }
};

ON RESUME我将此函数称为实际连接:

private void connectLogoTimerService() {
    Log.i(tag, "-connecting service");

    Intent intent = new Intent(this, LogoTimerService.class);
    startService(intent);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

    if (mService!=null) 
        Log.i(tag, "-SERVICE BOUND");
    else
        Log.i(tag, "-Service NOT bound");
}

当我第一次启动应用程序时,我得到第二个(未绑定)消息。

为什么不受约束?是慢吗? (看起来好像在玩耍。)

如果我没有销毁活动,则找到mService。

如何同步此功能,以便恢复状态?

我开始并绑定服务。这是对的吗?

我可以看到该服务正在使用此代码运行(我在此站点上找到了它,谢谢):

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager
            .getRunningServices(Integer.MAX_VALUE)) {
        if (LogoTimerService.class.getName().equals(
                service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

对你的第一个问题的回答是因为bindService是'async'。在调用onServiceConnected之前,您将输入if语句。