问题描述:

I saw how to send data from a thread declared into an Activity to this Activity itself. However, I don't know how to get data from a Service's thread and then send it to my Activity. I'm a bit confused, do I still need to use Handler?

EDIT: I have found the solution! Let's sum up. First, declare your Handler inside your Activity and before starting your Service, put some extra data by adding a new Messenger, linked to your Handler.

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);

}

}

Then, inside your Service class (you can do the same with an IntentService class), get your Messenger back and send it as a parameter to your Thread class:

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;

}

}

Once again, get your Messenger back into your Thread class:

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;

}

}

Finally, wherever you want to send your data, use this code:

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(); }

相关阅读:
Top