There is a service

package com.example.my.myapplication; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.UnknownHostException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.app.Service; import android.content.Intent; import android.os.AsyncTask; import android.os.IBinder; import org.greenrobot.eventbus.EventBus; public class MyService extends Service { Socket client = null; DataOutputStream dataToServerStream = null; DataInputStream dataFromServerStream = null; Boolean isConnected = false; ExecutorService es; public void onCreate() { super.onCreate(); es = Executors.newFixedThreadPool(1); } public void onDestroy() { super.onDestroy(); } public int onStartCommand(Intent intent, int flags, int startId) { String dataToServer = intent.getStringExtra("dataToServer"); //сервис может вызываться больше 1 раза, поэту проверяем был ли клиент уже подключен if (isConnected){ try { //если клиент уже был подключен, то это попытка отправки данных на сервер byte[] buf = dataToServer.getBytes("UTF-8"); dataToServerStream.write(buf, 0, buf.length); } catch (IOException e) { e.printStackTrace(); } } else{ //если клиент еще не подключался - то подключаемся MyRun mr = new MyRun(startId, dataToServer); es.execute(mr); } return super.onStartCommand(intent, flags, startId); } public IBinder onBind(Intent arg0) { return null; } //класс подключения к серверу class MyRun implements Runnable { String dataToServer; int startId; public MyRun(int startId, String dataToServer) { this.dataToServer = dataToServer; this.startId = startId; } public void run() { //подключение к серверу try { client = new Socket("193.1**.1*.2*", 1605); dataToServerStream = new DataOutputStream(client.getOutputStream()); dataFromServerStream = new DataInputStream(client.getInputStream()); isConnected = true; } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { System.out.println("Got an IOException: " + e.getMessage()); } //стартуем асинктаск приема данных с сервера GetDataFromServer GetData = new GetDataFromServer(); GetData.execute(); } } //асинктаск приема данных с сервера class GetDataFromServer extends AsyncTask<Void, String, Void> { @Override protected Void doInBackground(Void... voids) { //чтение данных с сервера while (true) { try { //String r = ""; byte[] readBuffer = new byte[5 * 1024]; //int read = 0; int read = dataFromServerStream.read(readBuffer); if (read != -1) { byte[] readData = new byte[read]; System.arraycopy(readBuffer, 0, readData, 0, read); try { String r = new String(readData, "UTF-8"); publishProgress(r); } catch (UnsupportedEncodingException e) { } } } catch (IOException e) { e.printStackTrace(); } } } //здесь мы отправляем данные в активити @Override protected void onProgressUpdate(String... values) { EventBus.getDefault().post(new MessageEvent(values[0])); } } } 

and activation code

 package com.example.my.myapplication; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import org.greenrobot.eventbus.EventBus; public class MainActivity extends Activity { EditText EditTextLogin; EditText EditTextPassword; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EditTextLogin = (EditText) findViewById(R.id.editTextLogin); EditTextPassword = (EditText) findViewById(R.id.editTextPassword); // создаем Intent для вызова сервиса Intent intent; intent = new Intent(this, MyService.class); // стартуем сервис startService(intent); EventBus.getDefault().register(this); } @Override protected void onDestroy() { super.onDestroy(); } //нажатие кнопки входа public void onClickEnter(View v) { Intent intent; String dataToServer = EditTextLogin.getText().toString(); intent = new Intent(this, MyService.class).putExtra("dataToServer", dataToServer); startService(intent); } // В этом методе-колбэке мы получаем наши данные // (объект `event` типа класса-модели MessageEvent) public void onEvent(MessageEvent event){ // извлекаем из модели отправленную строку: event.message = "Hello everyone!" EditTextLogin.setText(event.message); } } 

Messageevent

 package com.example.my.myapplication; public class MessageEvent { public final String message; public MessageEvent(String message) { this.message = message; } } 

The essence of this. When the activation starts, the service starts. the service connects to the server, then listen to the responses from the server. In the activation, when you click on the button, we send data to the server. but when you start the application, it crashes with an error

Caused by: org.greenrobot.eventbus.EventBusException: Subscriber class com.example.my.myapplication.MainActivity and its use

in line

 EventBus.getDefault().register(this); 

how to fix?

    1 answer 1

    In your error, it is literally said that you have a non-public method in @Subscribe with the annotation @Subscribe . Just add this annotation to the onEvent method onEvent