Answer the question
In order to leave comments, you need to log in
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();
}
// главная активити
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
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question