-2

I create a service to start a activity on button click.In first time activity is start but when I closed activity or leave as it is open than activity is start by service automatically.Pleas help me ,I want start activity only click on button not second time automatically by service class I use following code-

Service class

public class Myservise extends Service {
       @Override
       public IBinder onBind(Intent arg0) {
          return null;
       }

       @Override
       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 onCreate() {
        super.onCreate();
        Intent dialogIntent = new Intent(this, Demo.class);
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(dialogIntent);
    }
       @Override
       public void onDestroy() {
          super.onDestroy();
          Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
       }
        }

Main Activity

public class MainActivity extends Activity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
                }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

      // Method to start the service
       public void startService(View view) {
          startService(new Intent(getBaseContext(), Myservise.class));
       }
}

Second Activity

public class Demo extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo);
    }

}

Pleas help me .

Gauri Shankar
  • 91
  • 3
  • 9

1 Answers1

2

First you should return

return START_NOT_STICKY; 

in onStartCommand(..) in service.

and try to stop service on onDestroy();

Also refer This SO POST

Community
  • 1
  • 1
M D
  • 47,665
  • 9
  • 93
  • 114