听chrome自定义选项卡进度事件

问题描述:

我有一个应用程序使用Chrome custom tabs来打开一些链接,我需要在用户每次呆在Chrome上时每秒都有活动,或知道他在Chrome上呆多少次。对我来说,唯一的方法就是使用Service。有可能以不同的方式做到这一点吗?听chrome自定义选项卡进度事件

+0

这听起来像你想监听当自定义选项卡关闭时被触发的事件。它是否正确? – ade

+0

是的,如果我在回调中有用户会话的总时间,但最好是每X次都有一个事件。 – Dichoben

对于铬自定义选项卡的实现我已遵循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); 
    } 

为了使代码更健壮,你可能想存储的偏好或数据库布尔isCustomTabsLaunched和长customTabsEnterTime因此在任何情况下,这两个参数被摧毁,如同您的活动可能会破坏在后台用户久留在铬自定义选项卡中的时间。

+1

谢谢你的回答@Chitrang,你的解决方案的问题是如果你在Chrome浏览器中杀死了activity,'onResume()'永远不会调用,你将丢失数据:/ – Dichoben

+0

你如何去杀死活动?或者你的意思是杀死应用程序在这种情况下,没有解决方案将工作。 – Chitrang

创建YourBroadCastReceiver类,如下所示

public class YourBroadCastReceiver extends BroadcastReceiver { 

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

} 

开始您的自定义选项卡成功地创建报警的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();