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

android android-fragments android-intent android-service android-service-binding

517 观看


173 作者的声誉

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;

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


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() {

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

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

    service_btn = (Button) rootView.findViewById(;
    service_btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent svc = new Intent(getActivity(), BackgroundSoundService.class);
            try {

            } 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?
作者: Martin j 的来源 发布者: 2017 年 9 月 15 日

回应 (1)


213 作者的声誉


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.

作者: SSALPHAX 发布者: 15.09.2017 06:04
来自类别的问题 :