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
你'如果condition'是理由。 –