Friday, February 22, 2019

Update activity from service

To update activity from another activity, we use startActivityForResult, for service we use this.
Pretend that we need to receive a String pass back from service and set to textView t.
Declare to top of class.
BroadcastReceiver receiver;
TextView t;
Copy to below setContentView();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.vidu");
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//UI update here
String b = intent.getStringExtra(service.pass);
t.setText(b);
}
};
registerReceiver(receiver,filter);
In service, declare on top.
static String pass="";
Copy in to onCreate().

String back= "This is example text!";
Intent local = new Intent();
   local.setAction("com.example.vidu");
     local.putExtra(pass, back);
     sendBroadcast(local);
Declare service in file Manifest.xml.
  <service
            android:name=".myservice"
            android:enabled="true"
            android:exported="false" />

And destroy when exit class.
@Override
     protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);      

}

No comments:

Post a Comment