我有一个使用Chrome custom tabs
打开一些链接的应用程序,我需要在用户停留在Chrome上的所有时间中每秒都有事件,或者知道他在Chrome上停留了多少时间。对我来说,唯一的方法是使用 Service
.是否可以以不同的方式做?
按如下方式创建 YourBroadCastReceiver 类
public class YourBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Called every 60 seconds","called");
}
}
成功启动自定义选项卡后,创建警报挂起意图,该意图将每 60 秒触发一次您的 BroadCastReceiver。
// 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.getBroadcast(
context, _pendingIntentId, alarmIntent, 0).cancel();
对于chrome自定义标签的实现,我遵循了本教程,github链接。
我的解决方案基本上依赖于布尔值和System.currentTimeMillis()。
步骤 - 1 : 声明两个类全局变量,
private boolean isCustomTabsLaunched = false;
private long customTabsEnterTime;
步骤 - 2 :在启动 URL 时将上面的值设置为变量。
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 : 在恢复方法中计算停留时间。
@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);
}
为了使代码更健壮,您可能希望在首选项或数据库中存储布尔值isCustomTabsLaunch和long customTabsEnterTime,因此在任何情况下,这两个参数都会被破坏,因为如果用户长时间停留在chrome自定义选项卡中,您的活动可能会在后台被破坏。