2016-08-01 82 views

回答

0

修改我想通了,我可以通過使用訪問功能做到這一點。

@TargetApi(Build.VERSION_CODES.LOLLIPOP) 
public static String getForegroundProcess(Context context) { 
    String topPackageName = null; 
    UsageStatsManager usage = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE); 
    long time = System.currentTimeMillis(); 
    List<UsageStats> stats = usage.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*1000, time); 
    if (stats != null) { 
     SortedMap<Long, UsageStats> runningTask = new TreeMap<Long,UsageStats>(); 
     for (UsageStats usageStats : stats) { 
      runningTask.put(usageStats.getLastTimeUsed(), usageStats); 
     } 
     if (runningTask.isEmpty()) { 
      return null; 
     } 
     topPackageName = runningTask.get(runningTask.lastKey()).getPackageName(); 
    } 
    if(topPackageName==null) { 
     Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); 
     context.startActivity(intent); 
    } 

    return topPackageName; 
} 

現在不斷檢查所需的應用程序是否在前臺。

String fg=getForegroundProcess(getApplicationContext()); 
    if(fg != null && fg.contains("com.instagram.android")){ 
     startService(new Intent(getApplicationContext(), bdownload.class)); 
    }else { 
     stopService(new Intent(getApplicationContext(), bdownload.class)); 
    } 

我連續運行與作業service.Which上面的代碼可用於 棒棒糖以上。

0

目標棒棒糖及其以上的版本是的,你可以做到這一點的唯一方法是通過輔助服務。看看這個頁面瞭解如何創建它。 https://developer.android.com/training/accessibility/service.html他們還需要通過服務 - >輔助功能屏幕啓用該服務。

AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED您可以詢問前面的軟件包以確定Instigram是否在頂部。

你肯定不希望使用getRunningTasks因爲函數是在Android 5.0以上版本

相關問題