X
X
xne712472015-04-08 13:12:56
Android
xne71247, 2015-04-08 13:12:56

In which method to start the service?

In the main activity in the onCreate method, I start my service. Further, the service works, but if I rotate the screen, then the service starts accumulate and then one after another they start to be executed, but I would like it to be only 1 time when the main activity is launched. I am in the service in the onStartCommand method, in order not to respond to repeated calls, I perform the work of the thread 1 time

if(startId == 1) { // не реагировать на повторные вызовы
            mTask.execute();
        }

Is this correct or how to do it, tk. I'm a beginner I don't know this, anyone know, please help?
// главная активити
public class mactiv extends Activity{

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

        startService(new Intent(this, mservis.class));
    }    
}

// сервис
public class mservis extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {       

        AsyncTask<Void, Integer, Void> mTask = new AsyncTask<Void, Integer, Void>() {
            @Override
            protected Void doInBackground(Void... params) {                

                return null;
            }            

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);               
                stopSelf();
            }
        };

        if(startId == 1) { // не реагировать на повторные вызовы, если не выполнять проверку, то поток при смене ориентации вызовется повторно т.к. сервис вызывается в методе onCreate главной активити
            mTask.execute();
        }
        
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();        
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
IceJOKER, 2015-04-08
@xne71247

The service starts only once and the onCreate method of the service works once, in other cases the onStartCommand method works , how did you manage to start one service several times is not clear O_O

M
Marat S, 2015-04-08
@aratj

how do you start the service?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question