I need a WorkerClass that generates sequential numbers to print through a Callback Interface these numbers in the MainActivity and in a SegundaActivity when opened. My problem is that when SegundaActivity is open the MainActivity no longer receives the numbers that are being generated in the WorkerClass. Here is my code:
Class MainActivity
public class MainActivity extends AppCompatActivity implements MeuCallback {
private Button button1;
private MinhaWorkerClass minhaWorkerClass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SegundaActivity.class);
startActivity(intent);
}
});
minhaWorkerClass = minhaWorkerClass.getInstancia();
if (minhaWorkerClass != null) {
minhaWorkerClass.criaCallback(this);
}
}
@Override
public void imprimeNumero(int numero) {
Log.i("Rute", "MainActivity-Numero: " + numero);
}
}
Classe SegundaActivity
public class SegundaActivity extends AppCompatActivity implements MeuCallback {
private MinhaWorkerClass minhaWorkerClass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_segunda);
minhaWorkerClass = minhaWorkerClass.getInstancia();
if (minhaWorkerClass != null) {
minhaWorkerClass.criaCallback(this);
}
}
@Override
public void imprimeNumero(int numero) {
Log.i("Rute", "SegundaActivity-Numero: " + numero);
}
}
Class MyWorkerClass
public class MinhaWorkerClass {
private MeuCallback meuCallback;
private static MinhaWorkerClass instancia;
// Construtor privado:
private MinhaWorkerClass() {
constroiSequenciaNumeros();
}
public static synchronized MinhaWorkerClass getInstancia() {
if (instancia == null) {
instancia = new MinhaWorkerClass();
}
// Retorna sempre a unica instancia criada desta Classe:
return instancia;
}
public void criaCallback(MeuCallback meuCallback){
this.meuCallback = meuCallback;
}
private void constroiSequenciaNumeros() {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
if (meuCallback != null) {
meuCallback.imprimeNumero(i);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
Interface MyCallback
public interface MeuCallback {
void imprimeNumero(int numero);
}