2016-05-31 72 views
17

我有一個應用程序使用Chrome custom tabs來打開一些鏈接,我需要在用戶每次呆在Chrome上時每秒都有活動,或知道他在Chrome上呆多少次。對我來說,唯一的方法就是使用Service。有可能以不同的方式做到這一點嗎?聽chrome自定義選項卡進度事件

+0

這聽起來像你想監聽當自定義選項卡關閉時被觸發的事件。它是否正確? – ade

+0

是的,如果我在回調中有用戶會話的總時間,但最好是每X次都有一個事件。 – Dichoben

回答

1

對於鉻自定義選項卡的實現我已遵循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

2

創建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();