Android location updates in a Service

后端 未结 4 744
礼貌的吻别
礼貌的吻别 2020-12-09 05:58

I want to do something like this:

  • When my application starts I want to start a Service which should check my location

  • When the application g

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-09 06:37

    Try This code.. By using this you can find whether your application is in foreground or background. Hope this will help you.

    try {
        foreground = new ForegroundCheckTask().execute(ctx).get();
    }
    
    ======================================
    
    
    class ForegroundCheckTask extends AsyncTask {
    
    @Override
    protected Boolean doInBackground(Context... params) {
        final Context context = params[0].getApplicationContext();
        return isAppOnForeground(context);
    }
    
    private boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null) {
            return false;
        }
        final String packageName = context.getPackageName();
    
    
        String activePackageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
        if (activePackageName.equals(packageName)) {
            return true;
        }
        else{
            return false;
        }
    
    
    }
    
    }
    

提交回复
热议问题