Android: Check if service is running via. bindService

前端 未结 7 1455
心在旅途
心在旅途 2021-02-18 15:28

What would be the best way to check if an Android Service is running? I am aware of the ActivityManager API, but it seems like the use of the API is not advised for

7条回答
  •  花落未央
    2021-02-18 16:11

    in your activity u can simply check it by using instance of your service in my case i done it using

      button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
    
                Intent intent=new Intent(MainActivity.this, MyService.class);
                //startService(intent);
                bindService(intent,serviceConnection,BIND_AUTO_CREATE);
                if (myService!=null)
                {
                    myService.RecData(editText.getText().toString());
                }
            }
        });
    }
    
    ServiceConnection serviceConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Toast.makeText(MainActivity.this,"onServiceConnected called",Toast.LENGTH_SHORT).show();
            MyService.MyBinder myBinder= (MyService.MyBinder) iBinder;
            myService= myBinder.getServiceInstant();
            myService.SetActivity(MainActivity.this);
            myService.RecData(editText.getText().toString());
        }
    

提交回复
热议问题