Search code examples
androidandroid-fragmentsandroid-intentandroid-serviceandroid-service-binding

How to pass an intent from fragment class to a service class in android


I am new to android and I am learning the service in android , I have created a fragment in which I have a button.On that button click I need to show toast a message.

This is my service class -

public class BackgroundSoundService extends Service {
private static final String TAG = null;



@Override
public void onCreate() {
    super.onCreate();
    Log.d("tagg", "onCreate: inside service");
    Toast.makeText(getApplication(), "This is my Toast message!", Toast.LENGTH_LONG).show();

}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
}

I need to toast the message when the button in my fragment class clicked. This is my fragment class -

public class ConnectFragment extends Fragment {

Button service_btn;

public ConnectFragment() {
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_connect, container, false);

    service_btn = (Button) rootView.findViewById(R.id.service_button);
    service_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //start_service();
            Intent svc = new Intent(getActivity(), BackgroundSoundService.class);
            try {
                startActivity(svc);

            } catch (Exception e) {
                Log.d("tagg", "start_service:excception " + e);
            }

        }
    });


    return rootView;
}

public void start_service() {
    Intent svc = new Intent(getActivity(), BackgroundSoundService.class);




}

}

Now I am getting an exception

start_service:excception android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.arjunh.navigationdrawer/com.example.arjunh.navigationdrawer.BackgroundSoundService}; have you declared this activity in your AndroidManifest.xml?

Solution

  • Add service in your AndroidManifest.xml file

     <service android:name=".BackgroundSoundService">
    

    and start service from fragment like that

    getContext().startService(new Intent(getContext(),BackgroundSoundService.class));
    

    I hope its helpful for you.