【问题标题】:android service stops and again create when i close application当我关闭应用程序时,android服务停止并再次创建
【发布时间】:2013-01-09 10:24:34
【问题描述】:

我正在开发一个应用程序,我在其中实现了该服务。但是当我退出我的应用程序时,服务停止(但永远不会调用 onDestroy())然后再次启动(调用OnCreate())。

实际上,无论应用程序的状态如何,我都不想在创建服务后停止服务。 随着服务onCreate() 再次被调用,服务丢失了之前处理的数据。我尝试了START_STICKY 但没有运气。

那么,我怎样才能让我的服务继续运行?

这是我的服务代码,

public class ddservice extends Service{

public void onCreate() {
    super.onCreate();
    Log.e("dservice", "onCreate");
                  /*here i am processing some important data in
                background thread*/  
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("ddservice", "onDestroy");

    }

    @Override
    public void onStart(Intent intent, int startid) {
        super.onStart(intent, startid);
        Log.e("ddservice", "onStart");

    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        Log.e("ddservice", "onStartCommand");

        return START_STICKY;
    }   


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }   


}//service class ends here

我从 mainActivity 启动这个服务,

startService(new Intent(this, ddservice.class));

【问题讨论】:

  • 你能添加你用来启动服务的代码吗?
  • @Tapirboy:请查看已编辑的问题。
  • 嗯..可能相关吗? stackoverflow.com/questions/7211066/…已通过重启ADB和模拟器解决
  • 重启亚行无效。
  • @Tapirboy:谢谢你的链接,在单独的进程中运行服务解决了我的问题。

标签: android service oncreate


【解决方案1】:

你应该以前台Service.startForeground(int, Notification)启动你的服务

【讨论】:

  • 我实现了 Service.startForeground(int, Notification) 但导致了同样的问题。
  • 我把 stackoverflow.com/questions/3687200/… 代码放在 onStart();
  • onStart 自 API 级别 5 起已弃用且不再调用。你应该把它放在onCreate
  • 我把它放在 onCreate() 但同样的问题。
猜你喜欢
  • 1970-01-01
  • 2013-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多