Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

startService from class that does not extend Activity

I have created a class that extends IntentService, and I would like to start the service from a class that is not an Activity, therefore, I do not have access to a Context object. I could not find an example of this in the documentation or the web. Is it possible ?

like image 284
Alex Cartwright Avatar asked Dec 14 '12 15:12

Alex Cartwright


2 Answers

You will need to pass current Activity context to non Activity class for starting service from non-activity class as:

public class NonActivity {
  public Context context;

  public NonActivity(Context context){
    this.context=context;
  }

  public void startServicefromNonActivity(){
     Intent intent=new Intent(context,yourIntentService.class);
     context.startService(intent);
  }
}

and pass current context as:

public class AppActivity extends Activity {
    NonActivity nonactiityobj;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
                 nonactiityobj=new NonActivity(CuttentActivity.this);
                 //start service here
                 nonactiityobj.startServicefromNonActivity();
    }
}
like image 186
ρяσѕρєя K Avatar answered Oct 06 '22 09:10

ρяσѕρєя K


Use this code Start and Stop Service

public class MyService {

Context context ;

public MyService(Context cont) {
    this.context = context ;
}

public void StartMyService()
{
    Intent i = new Intent(context,YourService.class);
    context.startService(i);
}
public void StopMyService()
{
    Intent i = new Intent(context,YourService.class);
    context.stopService(i);
}
}

This just create object of this class

  MyService mySevice ;
  @Override
  public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  myService = new MyService(this);
  //For Startting Service
  myService.StartMyService();

  //For Stopping Service
  myService.StopMyService();
}
like image 30
Mohd Saleem Avatar answered Oct 06 '22 09:10

Mohd Saleem