我创建了一个服务,并且在activity中启动了它,它OnCreate,OnStart方法都被调用了,可以正常运行,但不知道为什么运行一到两个小时之后就会自动停止,我看了一下log,OnCreate方法会被再次调用,但OnStart方法就没有再被调用,所以导致服务就像停止了一样。在应用程序管理页面-》正在运行中的服务中还是可以看到我创建的服务,显示还在运行。但其实已经不work,服务中创建的线程已经不工作了。请问大家这是怎么回事?
我创建的服务也很简单,下面是服务的代码:package my.testservice;
import java.util.Date;import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class GSService extends Service { private boolean threadDisable=false;
private int count=0;
private SDFileMan mSDFFileMan = new SDFileMan("MyLog.txt");

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
} @Override
public void onCreate() {
super.onCreate();
String msg = "The service is created! DateTime:" + DateTimeUtil.FormatDateToString(new Date());
Log.e( "GSService" , msg);
mSDFFileMan.saveAppendLine(msg);
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
String msg = "The service is Started! DateTime:" + DateTimeUtil.FormatDateToString(new Date());
Log.e( "GSService" , msg);
mSDFFileMan.saveAppendLine(msg);
new Thread(new Runnable(){ @Override
public void run() {
while (!threadDisable) {
try {
                Thread.sleep( 3000 );
            } catch (InterruptedException e) {}
            count ++ ;
            Log.e( "GSService" , " Count is " + count);
            mSDFFileMan.saveAppendLine("GSService is running, Count= " + count +"! DateTime:" + DateTimeUtil.FormatDateToString(new Date()));
}
}}).start();
}

@Override
public void onDestroy() {
super .onDestroy();
threadDisable = true;
String msg = "The service is Destroyed! DateTime:" + DateTimeUtil.FormatDateToString(new Date());
Log.e( "GSService" , msg);
mSDFFileMan.saveAppendLine(msg);
}
}

解决方案 »

  1.   

    启动服务的方法就这几句:Intent i  = new Intent();  
    i.setClass(MyServiceTestActivity.this, GSService.class); 
    MyServiceTestActivity.this.startService(i);
      

  2.   

    看一下你有没有内存泄漏呢?
    service如果你想它运行的时间很长的话,最好是把它搞成foreground service,这样就不会给系统回收
      

  3.   

    那为什么不把墨迹天气的service回收了?它的也是后台的啊
      

  4.   

    墨迹的是foreground service,你没看到他在noticification把中有一个自己的item吗
      

  5.   

    onstart已经过时了,得重写onstartcommand这个,返回值为START_STICKY
    再试试。
      

  6.   

    Service的优先级要低于Activity,在系统资源不足的时候,Service可能被系统Destroy而回收,直到下一次被在此创建。你的情况下可以这样做,第一,在onStartCommand()方法中返回START_STICKY;第二,在onCreate()方法中设置setForeground(true);@Override  
    public void onCreate() {  
            super.onCreate();  
            setForeground(true);
    }  
      

  7.   

    onstartcommand里面第一句话,就是调用onstart.
    已经说过了,搞一个forgroundservice,看看apidemo中,怎么写吧。
      

  8.   

    setForeground已经不建议用了,去看看apidemo中怎么启动一个foregroundservice把,有一个文件名字是:ForegroundService.java
      

  9.   

    没解决,看来真的得弄个foreground的了。但我还是没看到墨迹天气有任何东西在我的notification bar里,里面只有一个金山手机卫士
      

  10.   

    要在Foreground运行service,只需要在Service中准备好相应的notification,方法和以前准备是一样的,只是最后调用的方法不是以前的mNotificationManager.notify方法,而是使用startForeground 方法