Reputation: 2527
I'm trying to connect my service and activity, tried different approaches, but nothing worked for me.
I start Servise in SplashActivity, when the app launches. Then Service do some work in background, and when this work is done, stopself()
method is calling in onStartCommand()
in Service.
Also there is another activity where should be results from this background work. The problem, that i need to load data into Recyclerview only when work is done and Service is stopped. So I Tried to use LocalBroadcastManager
and send message to the activity before stopself()
method.
The problem is, activity doesn't get any messages from Service. Here is my code, it's from this answer on stackoverflow - https://stackoverflow.com/a/8875292/7478869
Service:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
helper = ItemDatabaseHelper.getInstance(this);
preferences = getSharedPreferences(PREFERENCES, MODE_MULTI_PROCESS);
editor = preferences.edit();
helper.clearTable(Contacts_Contract.CONTACT_TABLE_NAME);
Set<ContactItem> setC = getContactList();
for(ContactItem item: setC){
helper.insertContacts(item);
}
editor.putBoolean(IS_CONTACTS_IMPORTED, true);
editor.apply();
Intent intent2 = new Intent("myevent");
// You can also include some extra data.
intent2.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent2);
Log.d(TAG, "onStartCommand: stopping service");
stopSelf();
return START_STICKY;
}
Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: starts");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("myevent"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.e("receiver", "Got message: " + message);
Toast.makeText(context, "Import completed", Toast.LENGTH_SHORT).show();
}
};
Upvotes: 1
Views: 566
Reputation: 1006614
Tactically, the reason why this does not work is that LocalBroadcastManager
is local to a process, and you have two processes.
Strategically, having this code in a separate process is unnecessary and dangerous. For example, you are relying on MODE_MULTI_PROCESS
, which has been deprecated for over two years and never worked especially well in the first place.
Upvotes: 1