【发布时间】:2020-04-08 19:45:32
【问题描述】:
我有一个 IntentService,它在 SplashActivity onCreate 调用时启动:
class SplashActivity : AppCompatActivity() {
private val handler = Handler(Looper.getMainLooper())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
startService(Intent(applicationContext, ContactsService::class.java))
handler.postDelayed({
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}, SPLASH_DELAY.toLong())
}
}
private const val SPLASH_DELAY = 1500
这是我的 IntentService :
override fun onHandleIntent(intent: Intent?) {
val cursor = ContactUtil.getContactsCursor(null, null, this)
val contacts = ContactUtil.getContacts(cursor, this)
cursor?.close()
val contactsIntent = Intent(CONTACTS_RECEIVER)
contactsIntent.putParcelableArrayListExtra(CONTACTS, ArrayList<Parcelable>(contacts))
sendBroadcast(contactsIntent)
}
1 - 如果我有大量联系人,我的 broadcastReceiver onReceive 方法会在 Fragment 创建后调用,这没关系。
2 - 如果我有几个片段,在片段创建之前调用 onReceive 方法,这根本不会更新我的 UI。
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
List<Contact> contacts = intent.getParcelableArrayListExtra(CONTACTS);
mContacts = contacts;
mAdapter.setItems(contacts, true);
mProgressBar.setVisibility(View.GONE);
mAppBarLayout.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
}
};
第二种情况的解决方案是什么?
【问题讨论】:
标签: android broadcastreceiver intentservice