将数据从服务的线程发送到活动

时间:2014-02-18 03:09:14

标签: java android multithreading service

我看到了如何将声明为Activity的线程中的数据发送到此Activity本身。但是,我不知道如何从服务的线程获取数据,然后将其发送到我的活动。我有点困惑,我还需要使用Handler吗?

编辑:我找到了解决方案!让我们总结一下。首先,在您的活动中声明您的处理程序,在启动您的服务之前,通过添加链接到您的处理程序的新Messenger来添加一些额外的数据。

public class HomeActivity extends ActionBarActivity
{
    ConnectionDetector m_cd;
    Intent m_networkListenerService;

    public Handler m_handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)  // This is where main activity thread receives messages
        {
            Bundle  bundle;
            if (msg.what == 1)  //  1 MEANS NEW ELEMENT
            {
                bundle = msg.getData();
                System.out.println( bundle.getString("name"));
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        this.m_networkListenerService = new Intent(this, Network.class);
        this.m_networkListenerService.putExtra("Messenger", new Messenger(this.m_handler));
        this.startService(this.m_networkListenerService);

    }
}

然后,在您的Service类中(您可以对IntentService类执行相同的操作),获取您的Messenger并将其作为参数发送到您的Thread类:

public class Network extends Service
{
    NetworkListenerThread  m_networkListenerThread;
    Messenger   m_messenger;

    @Override
    public void onCreate()  {   super.onCreate();   }

    @Override
    public void onDestroy() {   super.onDestroy();  }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        if (intent != null)
        {
            Bundle extras = intent.getExtras();
            if (extras != null)
            {
                this.m_messenger = (Messenger)extras.get("Messenger");
                this.m_networkListenerThread = new NetworkListenerThread(m_messenger);
                this.m_networkListenerThread.start();
            }
        }
        return Service.START_STICKY;
    }
}

再一次,让你的Messenger回到你的Thread类:

public class NetworkListenerThread extends Thread
{
    private static final int BROADCAST_PORT = 4415;
    private DatagramSocket  m_socket = null;
    private Messenger   m_messenger; 

    public  NetworkListenerThread(Messenger messenger)
    {
        this.m_messenger = messenger;
    }
}

最后,无论您要将数据发送到何处,请使用以下代码:

Message msg = Message.obtain();   //  Creates a message from the message handler to send it back to the main UI
msg.what = 1;   //  Specifies the type of message
Bundle bundle = new Bundle(1); //  Object of size 1 in which we put the data in
bundle.putString("name", name); //  Key + data (which is a String)
msg.setData(bundle); //  Attaches the bundle to the message
try {   this.m_messenger.send(msg); }  //  We use the Messenger from the main thread to send the data 
catch (RemoteException e) { e.printStackTrace();    }

0 个答案:

没有答案