粘性Service就是一种服务 把他删去他又会马上创建 原理是在这个服务中去开启线程不断检测此服务是否存在如果不存在,咋就会重新创建

 import android.app.Activity;
import android.content.Intent;
import android.os.Bundle; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); startService(new Intent(getApplicationContext(),PushService.class));
} }

MainActivity.java

 import java.util.List;

 import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class PushService extends Service { @Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate(); new SeekServiceThread().start();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;//绮樻�Service鏍囪瘑锛屽綋Service缁勪欢鍦ㄩ潪鎰忔効鏃惰鍋滄鍚庯紝鏈夋満鐜囬噸鍚�
} @Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
} //鏌ユ壘褰撳墠缁勪欢鐨勭嚎绋嬶紝濡傛灉褰撳墠姝h繍琛岀殑鏈嶅姟缁勪欢涓嶅寘鍚玃ushService缁勪欢鏃讹紝鍒欏惎鍔�
class SeekServiceThread extends Thread{ @Override
public void run() { while(true){ //1.鑾峰彇Activity缁勪欢绠$悊鍣紙绠$悊褰撳墠搴旂敤鐨勮繘绋嬨�鏈嶅姟缁勪欢銆佷换鍔℃垨鍥為�鏍堬級
ActivityManager mgr=(ActivityManager) getSystemService(ACTIVITY_SERVICE); //2. 鑾峰彇姝h繍琛岀殑鏈嶅姟缁勪欢
List<RunningServiceInfo> rServices = mgr.getRunningServices(100); boolean isFinded=false;//鏍囪瘑鏄惁鏌ユ壘鍒板綋鍓嶇殑service缁勪欢
for(RunningServiceInfo rService:rServices){
if(rService.getClass().getName().equals(PushService.class.getName())){
isFinded=true;
}
} if(!isFinded){ //濡傛灉娌℃湁鏌ユ壘鍒帮紝鍒欏惎鍔ㄦ湰鏈嶅姟缁勪欢 startService(new Intent(getApplicationContext(),PushService.class));
} try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
} }

PushService.java

05-08 15:08