收听Chrome自定义标签进度事件

时间:2016-05-31 14:10:22

标签: android chrome-custom-tabs

我有一个使用Chrome custom tabs打开某些链接的应用程序,我需要在用户停留在Chrome上的每一秒都有活动,或者知道他在Chrome上停留了多少时间。对我来说,唯一的方法是使用Service。有可能以不同的方式做到这一点吗?

2 个答案:

答案 0 :(得分:2)

按如下所示创建YourBroadCastReceiver类

public class YourBroadCastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Called every 60 seconds","called");
    }

}

成功启动自定义标签后,创建一个每隔60秒触发一次YourBroadCastReceiver的Alarm 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();

答案 1 :(得分:1)

为了实现Chrome自定义标签,我已经关注了this教程,github link

我的解决方案基本上依赖于布尔 System.currentTimeMillis()

步骤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);
        }
    });

步骤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自定义中长时间停留,您的活动可能会在后台销毁标签