How to transfer complex data between the Service and activity?

How to transfer complex data (for example, an employee) between the Service and Activity?

Here Service and activity are in different packages. There may be different applications.

+4
source share
2 answers
  • First serialize the object you want to pass.
  • Place the serialization object in advanced settings.
  • At the end of the reception, just get the serialized object, deserialize it.

eg,

Employee employee = new Employee(); 

then

 intent.putExtra("employee", serializeObject(employee)); 

upon admission

 byte[] sEmployee = extras.getByteArray("employee"); 

employee = (Employee) deserializeObject (sEmployee);

FYI,

 public static byte[] serializeObject(Object o) throws Exception,IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos); try { out.writeObject(o); // Get the bytes of the serialized object byte[] buf = bos.toByteArray(); return buf; } catch (IOException e) { Log.e(LOG_TAG, "serializeObject", e); throw new Exception(e); } finally { if (out != null) { out.close(); } } } public static Object deserializeObject(byte[] b) throws StreamCorruptedException, IOException, ClassNotFoundException, Exception { ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(b)); try { Object object = in.readObject(); return object; } catch (Exception e) { Log.e(LOG_TAG, "deserializeObject", e); throw new Exception(e); } finally { if (in != null) { in.close(); } } } 
+3
source

You need to create your own complex data object (for example, Employee), either using the Parcelable interface or Serializable .

Then create an Intent and use putExtra () , passing it a verbose or serializable object.

Then in the target class use getParcelableExtra () or getSerializableExtra () etc. to get this object.

+1
source

Source: https://habr.com/ru/post/1402364/


All Articles