服务中的OnStartCommand崩溃列表元素

时间:2016-08-22 11:21:32

标签: java android service

在标题中,我对绑定服务有一个非常奇怪的问题。

确保我的服务以两种方式运作。它由循环AlarmBroadcast(由public class MsgService extends Service { private static final String LOG_MSG = "MSG_SERVICE"; private final Context context = this; private List<Message> clients; private Messenger messenger = new Messenger(new IncomingHandler(this)); @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.v(LOG_MSG, "Message service started"); new AsyncMsgsDownloadManager(this).execute(); return START_STICKY; } @Override public IBinder onBind(Intent intent) { return messenger.getBinder(); } @Override public void onCreate() { Log.v(LOG_MSG, "Message service created"); HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND); thread.start(); exceptionHandler = new ExceptionHandler(); clients = Collections.synchronizedList(new ArrayList<Message>()); } @Override public void onDestroy() { Log.v(LOG_MSG, "Message service destroyed"); } private void sendResponseToClients() { Thread t = new Thread(new Runnable() { @Override public void run() { //update local database } }); t.join(); for(Message client : clients) { if ("TasksPerson".equals(client.obj)) { client.replyTo.send(Message.obtain(null, MSG.REFRESH_TASKS.ordinal())); break; } } } static class IncomingHandler extends Handler { private final WeakReference<MsgService> _service; IncomingHandler(MsgService msgService) { _service = new WeakReference<>(msgService); } @Override public void handleMessage(Message msg) { switch (MSG.getEnum(msg.what)) { case REGISTER_CLIENT: { _service.get().clients.add(msg); break; } case UNREGISTER_CLIENT: { _service.get().clients.remove(msg); break; } } } } static class AsyncMsgsDownloadManager extends AsyncTask<Void, Void, Void> { private final WeakReference<MsgService> service; AsyncMsgsDownloadManager(MsgService service) { this.service = new WeakReference<>(service); } @Override protected Void doInBackground(Void... voids) { //downloading data from server return null; } @Override protected void onPostExecute(Void result) { try { service.get().stopSelf(); } catch (NullPointerException e) { //Service already closed? } } } } )启动,用于下载数据,并且可以与客户端绑定。 服务下载数据到本地数据库,当一些特定客户端连接时,下载(将使用此数据)服务获取它并向客户端发送REFRESH标志,从而对数据库应用更改。

onStartCommand

问题是,当我将客户端消息绑定到我的服务时,一切都没问题 - 它出现在客户列表中,我可以通过客户端信使简单地发送消息。但是当某个客户端连接并且服务获取{{1}}列表崩溃时。

列表仍然引用了对象(我检查了它,它在android studio中的数字相同),但是这个对象如果只有null或零参数。

0 个答案:

没有答案