2014-10-09 136 views
0

我有一个从数据库获取用户消息的应用程序,如果有新消息,它会推送通知我使用该服务..该服务在打开应用程序或在应用程序中正常工作前景。但是当我关闭它,它不工作..它不被破坏或停止它只是不工作:SI不知道为什么。这是我的服务代码:服务代码在应用程序停止时停止

public class BGService extends Service { 

ArrayList<Message> messages = new ArrayList<Message>(); 
ArrayList<String> requests = new ArrayList<String>(); 
Timer timer = new Timer(); 
Timer timer2 = new Timer(); 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public void onDestroy() { 
    Log.d("Chat", "BGService Destroyed"); 
    timer.cancel(); 
    timer.purge(); 
    timer2.cancel(); 
    timer2.purge(); 
} 

@SuppressWarnings("unchecked") 
@Override 
public void onStart(Intent intent, int startId) { 
    Log.d("Chat", "BGService Started"); 
    messages = (ArrayList<Message>) intent.getExtras().get("messages"); 
    requests = (ArrayList<String>) intent.getExtras().get("requests"); 
    Log.d("Button Clicked", "Messages: " + messages); 

    new Timer().scheduleAtFixedRate(new TimerTask() { 
     public void run() { 
      Log.d("Service", "Running"); 
     } 
    }, 2000, 2000); 
} 
} 

回答

0

您告诉服务停止在您的代码中。因为你使用onBind(),看起来你并没有启动服务,而是反感。如果绑定到服务,那么当您的活动结束时,服务会自动结束。

如果您想保持服务正常运行。

  • ,而应用程序正在运行
  • 设置一个通知,以便服务是在前台
  • 更改舱单因此该服务启动,以保持业务运行
  • 绑定到该服务有一个服务的服务在一个单独的进程

启动该服务,所以你可以在onStartCommand(返回startsticky)告诉你想这是贴在

OS中运行
@Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     return Service.START_STICKY; 
    } 

启动服务。只有当您有连接与服务来回通信时才能绑定到服务。 ()这是从onBind返回

startService(new Intent(context, ServiceLocationRecorder.class)); 
    // bind to the service 
    if (!mIsBound) { 
     // Bind to the service 
     bindService(new Intent(context, 
       ServiceLocationRecorder.class), mConnection, 
       Context.BIND_AUTO_CREATE); 
     mIsBound = true; 
    } 

绑定到该服务用于设置粘结剂的处理程序,你可以和来自与服务进行通信。在onBind()中返回null将违反onBind()事件的目的,因此您可以跳过此代码。

/** 
* When binding to the service, we return an interface to our messenger for 
* sending messages to the service. 
*/ 
@Override 
public IBinder onBind(Intent intent) { 
    return mMessenger.getBinder(); 
} 

将服务设置为前台你做这个和os将不太可能结束你的服务来获得另一个应用程序的内存。

//this is done inside the service 
startForeground(R.id.action_record, getMyCustomNotification()); 

在自己的过程中运行该服务,然后GC将能够收集您的活动并保持服务运行。

<service 
     android:name="com.example.service" 


     android:process=":myseparateprocess" >s --> 
    </service>