当我关闭我的应用程序或我的应用程序被破坏时,我感到奇怪的服务行为。服务从beggining开始意味着再次onStartCommand()方法调用。如果服务在后台运行,则不应再次调用,请帮助我为什么会发生这种情况 这是我的服务代码
package gcmtutorial.androidbegin.com.socket;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* Created by shuser on 21-07-2016.
*/
public class Services extends Service {
public static boolean status;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public class Hello implements Runnable{
public void run(){
synchronized (this){
int i=0;
while (i<100){
try {
wait(1000);
Log.e("Status:", "value "+i);
i++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
stopSelf();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
status = true;
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Thread thread = new Thread(new Hello());
thread.start();
return START_STICKY;
}
@Override
public void onDestroy() {
status = false;
super.onDestroy();
Log.e("Status:","Service Destroyed");
}
}
这是我的MainActivity代码
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, Services.class);
if (Services.status == true) {
Log.e("Check:","Service is Running");
}else {
Log.e("Check:","Service Will run now");
startService(intent);
}
}
}
请帮助我为什么这样的事情发生在服务上。我得到Toast以及Service Started和LogCat也显示0的值
答案 0 :(得分:1)
如果此服务的进程在启动时被终止(从onStartCommand(Intent,int,int)返回后),则将其保持在启动状态但不要保留这个交付的意图。 稍后系统将尝试重新创建服务。因为它处于启动状态,所以它将保证在创建新服务实例后调用onStartCommand(Intent,int,int);
如果您希望自己的服务在销毁过程时不自动重启,请返回START_NOT_STICKY