I have an algorithm that generates prime numbers using a Service
. Well, it works but I need it to automatically update the data on my% s of% main, at the moment it does so with the click of a button and needs to be done automatically.
That is, send my Activity
always the last prime number generated in textView
automatically. Any idea? I am a beginner and would appreciate if they can be very specific with examples that I can use.
public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {
private Chronometer cro;
private TextView tvCampo;
private Contador.ContadorServiceBinder binder = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cro = (Chronometer) findViewById(R.id.cro);
tvCampo = (TextView) findViewById(R.id.campoTexto);
findViewById(R.id.botao).setOnClickListener(this);
startService(Contador.i(this));
bindService(Contador.i(this), this, BIND_AUTO_CREATE);
}
@Override
public void onClick(View v) {
cro.start();
tvCampo.setText(String.valueOf(binder.getPrimo()));
}
@Override
protected void onPause() {
super.onPause();
if (binder == null) {
unbindService(this);
binder = null;
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder = (Contador.ContadorServiceBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
binder = null;
}
}
Here is my service
that inherits from Activity
:
public class Contador extends Service {
public int primo = 0;
private Boolean ativo = false;
private ContadorServiceBinder binder = new ContadorServiceBinder();
public static Intent i(Context context) {
return new Intent(context, Contador.class);
}
@Override
public void onCreate() {
if (!ativo) {
ativo = true;
new Thread() {
public void run() {
int i = 2;
int j = 1;
int contador = 0;
while (i <= 1000000000) {
while (j <= i) {
if (i % j == 0) {
contador++;
}
j = j + 1;
}
if (contador == 2) {
primo = i;
}
i = i + 1;
j = 1;
contador = 0;
}
}
}.start();
}
}
@Override
public void onDestroy() {
super.onDestroy();
ativo = false;
primo = 0;
binder = null;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public class ContadorServiceBinder extends Binder {
public int getPrimo() {
return primo;
}
}
}