Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to start service from fragments

I want to start service from fragment from a list view item. I am trying to call service with:

startService(new Intent(getActivity(),myPlayService.class)); 

But it wont work at all. How do i call my service from fragments? Is there any another way to start service?

like image 992
Swap-IOS-Android Avatar asked Oct 22 '12 08:10

Swap-IOS-Android


2 Answers

Replace

startService(new Intent(getActivity(),myPlayService.class));

with

getActivity().startService(new Intent(getActivity(),myPlayService.class));

like image 168
DroidBender Avatar answered Sep 19 '22 14:09

DroidBender


To start service from a fragment use

Java

requireActivity().startService(new Intent(getContext(), ServiceName.class)); 

Kotlin

requireActivity().startService(Intent(context, ServiceName::class.java) 
like image 45
guest Avatar answered Sep 20 '22 14:09

guest