I have a timer but I want it to also run in the background, I created a new Service
, I think it works but I have a problem with it, I want also to change the layout
attributes, like changing TextView
text using setText
method, I prefer doing it with BroadCastReceiver
so I have the following code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
textView.setText("hey");
}
};
registerReceiver(receiver, filter);
buttonStart = (Button) findViewById(R.id.start);
buttonStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startService(new Intent(MainActivity.this, LocalService.class));
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
I registered here the Receiver
so it will happen when I am broadcasting from the Service
and change the text to "hey" - I wanted it just to check if the broadcast is working. on the Service
I used a code that runs a timer and when it start it will broadcast the message, it is the first time I am using broadcasting receiver
for sending actions
and not just to wait until Bluetooth
is on and stuff like this, here is my Service
code:
public class LocalService extends Service
{
private static Timer timer = new Timer();
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
startService();
}
private void startService()
{
timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
}
private class mainTask extends TimerTask
{
public void run()
{
Intent intent = new Intent();
intent.setAction("SOME_ACTION");
sendBroadcast(intent);
}
}
public void onDestroy()
{
super.onDestroy();
}
}
Thanks for helping.