-2

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?
Aditi Parikh
  • 1,522
  • 3
  • 13
  • 34
Martin j
  • 511
  • 1
  • 9
  • 31

1 Answers1

0

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.

Shivam Sharma
  • 290
  • 2
  • 14
  • can you please tell me the difference between this getActivity().startService(svc); and getContext().startService(new Intent(getContext(),BackgroundSoundService.class)); @SSALPHAX – Martin j Sep 15 '17 at 06:10
  • @Martinj see this link https://stackoverflow.com/questions/30278290/what-is-the-difference-between-this-getcontext-and-getactivity – Shivam Sharma Sep 15 '17 at 06:15