У меня есть приложение, использующее Chrome custom tabs
, чтобы открыть некоторые ссылки, мне нужно иметь событие каждую секунду в течение всего времени пребывания пользователя в Chrome или знать, сколько раз он остается в Chrome. Для меня единственный способ сделать это - использовать Service
. Можно ли сделать это по-другому?
Прослушать хроном пользовательский вкладку
Ответ 1
Создайте свой класс YourBroadCastReceiver следующим образом
public class YourBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Called every 60 seconds","called");
}
}
После запуска вашей пользовательской вкладки создайте Alarm PendingIntent, который будет запускать YourBroadCastReceiver один раз каждые 60 секунд.
// Retrieve a PendingIntent that will perform a broadcast
Intent repeatingIntent = new Intent(context,
YourBroadCastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, _pendingIntentId, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Set the alarm to start at 10:00 AM
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
manager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 60 * 1000, // repeat for every 60 seconds
pendingIntent);
после закрытия вашей вкладки никогда не забывайте отменить свой PendingIntent
PendingIntent.getBroadcast(
context, _pendingIntentId, alarmIntent, 0).cancel();
Ответ 2
Для реализации пользовательских вкладок chrome я следил за этим учебником, github ссылка.
Мое решение в основном полагается на boolean и System.currentTimeMillis().
Шаг - 1: Объявить две глобальные переменные класса,
private boolean isCustomTabsLaunched = false;
private long customTabsEnterTime;
Шаг - 2: Задайте значения выше для переменных при запуске.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "FloatingActionButton");
// Launch Chrome Custom Tabs on click
customTabsIntent.launchUrl(CustomTabsActivity.this, Uri.parse(URL));
isCustomTabsLaunched = true;
customTabsEnterTime = System.currentTimeMillis();
Log.d(TAG, "customTabsEnterTime = " + customTabsEnterTime);
}
});
Шаг - 3: Рассчитайте время пребывания в методе onResume.
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
if (isCustomTabsLaunched) {
isCustomTabsLaunched = false;
calculateStayTime();
}
}
private void calculateStayTime() {
long customTabsExitTime = System.currentTimeMillis();
Log.d(TAG, "customTabsExitTime = " + customTabsExitTime);
long stayTime = (customTabsExitTime - customTabsEnterTime) / 1000; //convert in seconds
Log.d(TAG, "stayTime = " + stayTime);
}
Чтобы сделать код более надежным, вы можете захотеть сохранить boolean isCustomTabsLaunched и long customTabsEnterTime в настройках или в базе данных, поэтому в любом случае эти два параметра будут уничтожены, так как ваша активность может быть уничтожена в фоновом режиме, если пользователь останется надолго в chrome custom вкладка.