update ui from background service in android using Broadcast Receiver.

The first thing that needs to be done is to create a string called BROADCAST_ACTION, this is simply a string that identifies what kind of action is taking place. Most of the time, it’s common to use the package name with the kind of action added to the end, so we’ll do that here. The next step is to create a handler that will be used to broadcast our data every 5 seconds. It’s better to use a Timer instead of Handler.

In onCreate, I’ve created a Intent and passed the BROADCAST_ACTION to the constructor of the intent. Notice that the Intent was defined as a global variable above. The intent will be called repeatedly in the Timer below and there is no reason to create a new intent every 5 seconds, so I’ll create it once here.

MainActivity.Java

public class MainActivity extends AppCompatActivity {
    TextView textview;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textview=(TextView)findViewById(R.id.textview);
    }
    @Override
    protected void onStart() {
        super.onStart();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MyService.MY_ACTION);
        registerReceiver(broadcastReceiver, intentFilter);
        //Start our own service
        Intent intent = new Intent(MainActivity.this,
                com.apps.broadcastrapp.MyService.class);
        startService(intent);
        super.onStart();
    }
    /*@Override
    protected void onStop() {
        // TODO Auto-generated method stub
        unregisterReceiver(myReceiver);
        super.onStop();
    }*/
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int datapassed = intent.getIntExtra("DATAPASSED", 0);
            String s = intent.getAction().toString();
            String s1 = intent.getStringExtra("DATAPASSED");
            textview.setText(s1);
            Toast.makeText(context,
                    "Triggered by Service!\n"
                            + "Data passed: " + String.valueOf(s1),
                    Toast.LENGTH_LONG).show();
        }
    };
}

MyService.java class

public class MyService extends Service {

    final static String MY_ACTION = "MY_ACTION";
    private static Context context;
    private Timer timer;
    public  String Data;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub

        MyThread myThread = new MyThread();
        myThread.start();

        return super.onStartCommand(intent, flags, startId);
    }

    public class MyThread extends Thread{

        @Override
        public void run() {
            // TODO Auto-generated method stub

            try {
                int delay = 1000; // delay for 1 sec.
                int period = 12 * 1000; // repeat every 120 sec.
                timer = new Timer();
                timer.scheduleAtFixedRate(new TimerTask() {
                    public void run() {
                        Calendar c = Calendar.getInstance();
                        Data = String.valueOf((c.get(Calendar.MILLISECOND)));
                        Intent intent = new Intent();
                        intent.setAction(MY_ACTION);
                        intent.putExtra("DATAPASSED", Data);
                        sendBroadcast(intent);
                    }
                }, delay, period);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            stopSelf();
        }

    }

}

Leave a comment