我想要运行的后台服务的实例

时间:2018-04-03 07:59:53

标签: android android-service

在这种情况下,服务已重复创建,但我需要获取运行服务的实例,以便我可以启动计时器任务。此服务的对象可以从任何活动中获取。基本目标是在特定按钮单击后启动计时器任务。

   public class MainActivity extends Activity {
        MyService mService;
        boolean mBound = false;
        int b=0;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            findViewById(R.id.btn_start_timer).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mBound) {
                       mService.runTimerTask(++b);
                    }
                }
            });
        }

        @Override
        protected void onStart() {
            super.onStart();
            // Bind to LocalService
            Intent intent = new Intent(this, MyService.class);
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        }

        @Override
        protected void onStop() {
            super.onStop();
            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
                MyService.LocalBinder binder = (MyService.LocalBinder) service;
                mService = binder.getService();
                mBound = true;
            }

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

1 个答案:

答案 0 :(得分:0)

您可以创建一个ServiceManager类并通过它路由所有方法并将其存储在应用程序中:

AWS Certificate Manager

在MainActivity中:

public class YourApplication extends Application {
  ...
  private ServiceManager serviceManager = ...;

  public ServiceManager getServiceManager() {
    return serviceManager;
  }
}

ServiceManager将处理解除绑定等以及涉及服务状态的所有方法。因此,您只需向ServiceManager询问正在运行的服务。在ServiceManager serviceManager = ((YourApplication)getApplication()).getServiceManager(); MyService runningService = serviceManager.getRunningService(); 完成工作的地方,将该工作委托给ServiceManager,以便它可以保持状态并与应用程序的其余部分共享:

ServiceConnection::onServiceConnected

这是在应用程序中共享对象状态的一般技术,但您需要根据应用程序进行定制。