简体   繁体   English

Android-活动和服务之间在另一个线程中进行通信

[英]Android - Communication between Activity and Service in another Thread

I am writing a Tracking App in Android. 我正在用Android编写跟踪应用程序。

I have got a Service implements LocationListener, which does all the stuff with location and writing to database, and Activity. 我有一个Service实现LocationListener,它完成所有与位置有关的工作,并写入数据库和Activity。

I would like to run Service in new thread to optimize my app. 我想在新线程中运行Service以优化我的应用程序。 I want also to send both sides messsages from Service to Activity, which will show info about location. 我还希望将双方的信息从“服务”发送到“活动”,以显示有关位置的信息。

I bind service, like it is mentioned in Bind to Service section and implement using a Messenger. 我绑定服务,就像在“ 绑定到服务”部分中提到的那样并使用Messenger实施。 Next I tried to do: 接下来我尝试做:

 Thread t = new Thread(){
        public void run(){
            bindService(new Intent(this, GPSLogger.class), mConnection, Context.BIND_AUTO_CREATE);
        }
    };
    t.start();

App is working, but all the GPSLogger stuff is doing in main thread. 应用程序正在运行,但是所有GPSLogger东西都在主线程中运行。

Is it any way to repair this? 有什么办法可以修复吗?

Regular services run in main thread. 常规服务在主线程中运行。

You can use IntentService instead. 您可以改用IntentService It is a job queue with a single bg thread. 这是一个具有单个bg线程的作业队列。

If you insist on using the base Service class then you'll have to spawn your own threads. 如果坚持使用基本Service类,则必须产生自己的线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM