1

New to android programming. Could you please let me know how to pass the view as parameter?

public class MainActivity extends ActionBarActivity {
  ...
  public void stopService(View view) {
    stopService(new Intent(getBaseContext(), MyService.class));
  }
}

public class MySmsReceiver extends BroadcastReceiver {
  ...
  MainActivity obj = new MainActivity();
  obj.stopService();
}

I have coded MyService.java correctly.

Thank you

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
kumar
  • 43
  • 1
  • 6
  • see here http://stackoverflow.com/questions/5301891/android-start-service-with-parameter –  Jan 12 '15 at 07:40
  • I am slowing understanding this. right now, this seems to work ... `context.startService(new Intent(context, MyService.class)); context.stopService(new Intent(context, MyService.class));` Thanks for all the links. – kumar Jan 14 '15 at 11:03

1 Answers1

2

At first you have to unbind the service from the previous activity in onStop(). Otherwise you may met a window leaked exception.

Place the code to stop the service in the Application class.

public class AppController extends Application {
  private static AppController mInstance;

  public static synchronized AppController getInstance() {
    return mInstance;
  }
  .........

  public void stopService(View view) {
    stopService(new Intent(getBaseContext(), MyService.class));
  }
}

Then you can get the Application object from any class and you will be able to stop the service from any activity, but before that you have to unbind the service from the other activity in onStop().

To stop the service from anywhere, call:

AppController.getInstance().stopService();
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
JIthin
  • 1,413
  • 1
  • 13
  • 29
  • hi User, Can you please explain this in detail. Or please provide an example? I have onStartCommand() and onDestroy in MyService.java. public int onStartCommand(Intent intent, int flags, int startId) { // Let it continue running until it is stopped. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); } – kumar Jan 12 '15 at 09:24
  • if your service is binded service, then you have to call unboundService() from the same context.check this http://stackoverflow.com/questions/8614335/android-how-to-safely-unbind-a-service – JIthin Jan 13 '15 at 03:21
  • Worked for me... Thank you, you saved me from a big headache :) – Silas May 26 '16 at 17:16