2016-07-23 137 views
1

当我关闭我的应用程序或我的应用程序遭到损坏时,我感觉有服务的奇怪行为。服务从启动开始意味着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); 
     } 
    } 
} 

请帮我为什么这样的事情也发生与服务。我得到吐司以及服务启动logcat中还显示了从0

+0

你'如果condition'是理由。 –

回答

1

START_STICKY值:

如果同时启动(从onStartCommand(意向,INT,INT返回后该服务的过程中被杀害)),然后将其保持在开始状态,但不保留这个交付的意图。 稍后系统将尝试重新创建该服务。因为它处于启动状态,它将保证在创建新的服务实例后调用onStartCommand(Intent,int,int);

如果你想你的服务你的进程被破坏没有自动重启,恢复START_NOT_STICKY

相关问题