startService from class that does not extend Activity

Alex Cartwright picture Alex Cartwright · Dec 14, 2012 · Viewed 10.3k times · Source

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 ?

Answer

ρяσѕρєя K picture ρяσѕρєя K · Dec 14, 2012

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();
    }
}