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 观看

1回复

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;



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

回应 1


0

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 发布者: 2017 年 9 月 15 日
来自类别的问题 :
32x32