Search code examples
androidservicefragment

Delete a running Service from a different activity Android


I start a service to see the accelerometer data on my main activity, and I have a button on a fragment and I want to finish my service with that button but I keep getting this error

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Context.stopService(android.content.Intent)' on a null object reference

This is my mainactivity where I create the service


public class FragmentManager extends AppCompatActivity {
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onPressStartService(Background_accelerometer.TAG);
    }

    public void onPressStartService(final String tag){
        Log.e(LOG_TAG,"start");
        intent = new Intent(FragmentManager.this, Background_accelerometer.class);
        intent.addCategory(tag);
        startService(intent);

    }
    public void onPressStopService(final String tag){
        intent = new Intent(FragmentManager.this, Background_accelerometer.class);
        intent.addCategory(tag);
        stopService(intent);
    }
}

This is my service

public class Background_accelerometer extends Service implements SensorEventListener {
    public static final String TAG = "MyServiceTag";
    public Background_accelerometer() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        Log.d("Service Started","Service Started");
        mInitialized = false;
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        return START_STICKY;
    }

and this my fragment with the button

public class FragmentDeveloper_2  extends Fragment {

    FragmentManager FM = new FragmentManager();
    Button stopBtn;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_developer, container, false);
        stopBtn = (Button) view.findViewById(R.id.button_stop);
        stopBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                FM.onPressStopService(Background_accelerometer.TAG);

            }
        });


        return view;

    }

How can I put a tag on my service to be able to close it or call it back from other activities?


Solution

  • There's a problems with this line:

    FragmentManager FM = new FragmentManager();
    

    Your class name causes confusion, it's not a FragementManager but an Activity. Activities cannot be instantiated by you, like this.

    What you need make the host Activity of your fragment to execute onPressStopService() is to let it know through a ViewModel. You could also do it through registering a callback but now ViewModel is the documented method.

    Otherwise you could also take a shortcut and run directly:

    stopBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                     Activity a = requireActivity()
                     Intent intent = new Intent(a, Background_accelerometer.class);
                     intent.addCategory(tag);
                     a.stopService(intent);
                }
            });