我有一个应用程序Chrome custom tabs
用来打开一些链接,我需要在用户停留在 Chrome 上的所有时间内每秒都有一个事件,或者知道他在 Chrome 上停留了多少时间。对我来说,唯一的方法是使用Service
. 有可能以不同的方式做吗?
问问题
1606 次
2 回答
2
如下创建您的 YourBroadCastReceiver 类
public class YourBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Called every 60 seconds","called");
}
}
启动自定义选项卡后,成功创建将每 60 秒触发一次 YourBroadCastReceiver 的警报 PendingIntent。
// 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();
于 2016-06-14T13:07:51.263 回答
1
为了实现 chrome 自定义选项卡,我遵循了本教程,github链接。
我的解决方案基本上依赖于boolean和System.currentTimeMillis()。
Step - 1:声明两个类全局变量,
private boolean isCustomTabsLaunched = false;
private long customTabsEnterTime;
步骤 - 2:在 launchUrl 时将上述值设置为变量。
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);
}
});
Step - 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);
}
为了使代码更健壮,您可能希望将布尔值 isCustomTabsLaunched 和 long customTabsEnterTime 存储在首选项或数据库中,因此无论如何这两个参数都会被破坏,因为如果用户在 chrome 自定义选项卡中长时间停留,您的活动可能会在后台被破坏。
于 2016-06-13T06:04:14.160 回答