下面列出了android.content.pm.ComponentInfo#android.app.ActivityManager 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static boolean isActivityRunning(Context context, String className) {
Intent intent = new Intent();
intent.setClassName(context, className);
ComponentName cmpName = intent.resolveActivity(context.getPackageManager());
boolean flag = false;
if (cmpName != null) {
ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfoList =
am.getRunningTasks(10);
for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
if (taskInfo.baseActivity.equals(cmpName)) {
flag = true;
break;
}
}
}
return flag;
}
public static String getProcessName() {
try {
ActivityManager activityManager = (ActivityManager) AnalysysUtil.getContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningApps = null;
if (activityManager != null) {
runningApps = activityManager.getRunningAppProcesses();
}
if (runningApps == null) {
return "";
}
String process = "";
for (ActivityManager.RunningAppProcessInfo proInfo : runningApps) {
if (proInfo.pid == android.os.Process.myPid()) {
if (proInfo.processName != null) {
process = proInfo.processName;
}
}
}
return process;
} catch (Throwable ignore) {
ExceptionUtil.exceptionThrow(ignore);
return "";
}
}
/**
* 程序是否在前台运行
*
* @param context
* @return
*/
public static boolean isRunningForeground(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
String curPackageName = context.getPackageName();
List<ActivityManager.RunningAppProcessInfo> app = am.getRunningAppProcesses();
if(app==null){
return false;
}
for(ActivityManager.RunningAppProcessInfo a:app){
if(a.processName.equals(curPackageName)&&
a.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
return true;
}
}
return false;
}
/**
* Starts an {@link AlertDialog} prompt and if accepted will clear the app's data or just opens
* the app's info menu if SDK < 19
*/
public static void promptUserToClearData(final Context ctx) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
new AlertDialog.Builder(ctx)
.setTitle("Clear App Data")
.setMessage("Do you really want to clear the whole app data? This cannot be undone.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.KITKAT)
public void onClick(DialogInterface dialog, int whichButton) {
((ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE))
.clearApplicationUserData();
}
})
.setNegativeButton(android.R.string.no, null).show();
} else {
ctx.startActivity(getAppInfoIntent(ctx));
}
}
/**
* Enables or disables the disk cache for the life of the application. This method cannot be
* called more than once per lifetime of the app and should therefore be called only during
* application startup; subsequent calls have no effect on the disk cache state.
*
* Note that when enabling Piccaso cache indicators, you may still find that some images appear
* as though they've been loaded from disk. This will be true for any app-packaged drawable or
* bitmap resource that's placed by Picasso. (These are always "from disk" with or without the
* presence of a disk cache.) Similarly, it's possible to get green-tagged images when using
* Picasso to "load" manually pre-loaded BitmapDrawables.
*
* @param diskCacheEnabled
*/
public static void setConfiguration(Context context, boolean diskCacheEnabled, Integer cacheHeapPercent) {
try {
Picasso.Builder builder = new Picasso.Builder((ArcusApplication.getContext()));
if (diskCacheEnabled) {
builder.downloader(new OkHttp3Downloader(new OkHttpClient()));
}
if (cacheHeapPercent != null) {
ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
int heapSize = (int) ((float)(1024 * 1024 * memoryClass) * ((float) cacheHeapPercent / 100.0));
builder.memoryCache(new LruCache(heapSize));
logger.debug("Setting Picasso in-memory LRU cache max size to {} bytes; {}% of heap sized {}", heapSize, cacheHeapPercent, 1024 * 1024 * memoryClass);
}
Picasso.setSingletonInstance(builder.build());
} catch (IllegalStateException e) {
logger.warn("Picasso setConfiguration() has already been called; ignoring request.");
}
}
void removePowerSaveTempWhitelistAppChecked(String packageName, int userId)
throws RemoteException {
getContext().enforceCallingPermission(
Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
"No permission to change device idle whitelist");
final int callingUid = Binder.getCallingUid();
userId = ActivityManager.getService().handleIncomingUser(
Binder.getCallingPid(),
callingUid,
userId,
/*allowAll=*/ false,
/*requireFull=*/ false,
"removePowerSaveTempWhitelistApp", null);
final long token = Binder.clearCallingIdentity();
try {
removePowerSaveTempWhitelistAppInternal(packageName, userId);
} finally {
Binder.restoreCallingIdentity(token);
}
}
private void applyTheme() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int customPrimaryColor = sharedPreferences.getInt(getString(R.string.pref_key_color_primary), -1);
int customAccentColor = sharedPreferences.getInt(getString(R.string.pref_key_color_accent), -1);
boolean isDarkTheme = sharedPreferences.getBoolean(getString(R.string.pref_key_dark_theme), false);
getTheme().applyStyle(CustomColorHelper.getPrimaryColorTheme(this, customPrimaryColor), true);
getTheme().applyStyle(CustomColorHelper.getAccentColorTheme(this, customAccentColor), true);
if (isDarkTheme) {
getTheme().applyStyle(R.style.DarkTheme, true);
} else {
getTheme().applyStyle(R.style.LightTheme, true);
}
// set recents app color to the primary color
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_round);
ActivityManager.TaskDescription taskDesc = new ActivityManager.TaskDescription(getString(R.string.app_name), bm, customPrimaryColor);
setTaskDescription(taskDesc);
}
/**
* 判断某个界面是否在前台
*
* @param context
* @param className 某个界面名称
*/
public static boolean isForeground(Context context, String className)
{
if (context == null || TextUtils.isEmpty(className))
{
return false;
}
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
if (list != null && list.size() > 0)
{
ComponentName cpn = list.get(0).topActivity;
if (className.equals(cpn.getClassName()))
{
return true;
}
}
return false;
}
/**
* APP是否在运行中(前台或后台)
* @param context
* @return
*/
public static boolean appIsRunning(Context context) {
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
if (am == null) {
return false;
}
List<ActivityManager.RunningAppProcessInfo> appList = am.getRunningAppProcesses();
if (appList == null) {
return false;
}
for (ActivityManager.RunningAppProcessInfo appInfo : appList) {
if (context.getPackageName().equals(appInfo.processName)) {
return true;
}
}
return false;
}
/**
* This method will find which router service is running. Use that info to find out more about that app and service.
* It will store the found service for later use and return the package name if found.
* @param pm An instance of a package manager. This is no longer used so null can be sent.
* @return
*/
public ComponentName componentNameForServiceRunning(PackageManager pm){
if(context==null){
return null;
}
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//PackageManager pm = context.getPackageManager();
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
//Log.d(TAG, service.service.getClassName());
//We will check to see if it contains this name, should be pretty specific
if ((service.service.getClassName()).toLowerCase(Locale.US).contains(SdlBroadcastReceiver.SDL_ROUTER_SERVICE_CLASS_NAME)){
//this.service = service.service; //This is great
if(service.started && service.restarting==0){ //If this service has been started and is not crashed
return service.service; //appPackageForComponenetName(service.service,pm);
}
}
}
return null;
}
/**
* Return whether application is foreground.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isAppForeground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (am == null) {
return false;
}
List<ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
if (info == null || info.size() <= 0) {
return false;
}
for (ActivityManager.RunningAppProcessInfo aInfo : info) {
if (aInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
if (aInfo.processName.equals(context.getPackageName())) {
return true;
}
}
}
return false;
}
/**
* check the application process name if process name is not qualified, then we think it is a service process and we will not init SDK
* @param pID
* @return
*/
private String getAppName(int pID) {
String processName = null;
ActivityManager am = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = appContext.getPackageManager();
while (i.hasNext()) {
ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
try {
if (info.pid == pID) {
CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
// Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
// info.processName +" Label: "+c.toString());
// processName = c.toString();
processName = info.processName;
return processName;
}
} catch (Exception e) {
// Log.d("Process", "Error>> :"+ e.toString());
}
}
return processName;
}
private void applyTheme() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int customPrimaryColor = sharedPreferences.getInt(getString(R.string.pref_key_color_primary), -1);
int customAccentColor = sharedPreferences.getInt(getString(R.string.pref_key_color_accent), -1);
isDarkTheme = sharedPreferences.getBoolean(getString(R.string.pref_key_dark_theme), false);
getTheme().applyStyle(CustomColorHelper.getPrimaryColorTheme(this, customPrimaryColor), true);
getTheme().applyStyle(CustomColorHelper.getAccentColorTheme(this, customAccentColor), true);
if (isDarkTheme) {
getTheme().applyStyle(R.style.DarkTheme, true);
} else {
getTheme().applyStyle(R.style.LightTheme, true);
}
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
getWindow().setStatusBarColor(typedValue.data);
// set recents app color to the primary color
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_round);
ActivityManager.TaskDescription taskDesc = new ActivityManager.TaskDescription(getString(R.string.app_name), bm, customPrimaryColor);
setTaskDescription(taskDesc);
}
public static void cleanMemory(Context context){
System.out.println("---> 清理前可用内存:"+getAvailMemory(context)+"MB");
ActivityManager activityManager=(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> processList = activityManager.getRunningAppProcesses();
if (processList != null) {
for (int i = 0; i < processList.size(); ++i) {
RunningAppProcessInfo runningAppProcessInfo= processList.get(i);
// 一般数值大于RunningAppProcessInfo.IMPORTANCE_SERVICE
// 的进程即为长时间未使用进程或者空进程
// 一般数值大于RunningAppProcessInfo.IMPORTANCE_VISIBLE
// 的进程都是非可见进程,即在后台运行
if (runningAppProcessInfo.importance > RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
String[] pkgList = runningAppProcessInfo.pkgList;
for (int j = 0; j < pkgList.length; ++j) {
System.out.println("===> 正在清理:"+pkgList[j]);
activityManager.killBackgroundProcesses(pkgList[j]);
}
}
}
}
System.out.println("---> 清理后可用内存:"+getAvailMemory(context)+"MB");
}
private Intent parseIntentAndUser() throws URISyntaxException {
mTargetUser = UserHandle.USER_CURRENT;
mBrief = false;
mComponents = false;
Intent intent = Intent.parseCommandArgs(this, new Intent.CommandOptionHandler() {
@Override
public boolean handleOption(String opt, ShellCommand cmd) {
if ("--user".equals(opt)) {
mTargetUser = UserHandle.parseUserArg(cmd.getNextArgRequired());
return true;
} else if ("--brief".equals(opt)) {
mBrief = true;
return true;
} else if ("--components".equals(opt)) {
mComponents = true;
return true;
}
return false;
}
});
mTargetUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Binder.getCallingUid(), mTargetUser, false, false, null, null);
return intent;
}
/**
* Check if specified service is running or not
* @param context
* @param cls name of service
* @return boolean is running or not
*/
private static boolean isRunningService(Context context, Class<?> cls) {
boolean isRunning = false;
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> info = activityManager.getRunningServices(Integer.MAX_VALUE);
if (info != null) {
for(ActivityManager.RunningServiceInfo serviceInfo : info) {
ComponentName compName = serviceInfo.service;
String className = compName.getClassName();
if(className.equals(cls.getName())) {
isRunning = true;
break;
}
}
}
return isRunning;
}
/**
* watch for memory usage and heap size per seconds
*/
public void run() {
mTimerTask = new TimerTask() {
@Override
public void run() {
MemoryInfo memoryInfo = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Activity.ACTIVITY_SERVICE);
activityManager.getMemoryInfo(memoryInfo);
Runtime runtime = Runtime.getRuntime();
String msg = String.format("free:%s%% %sKB total:%sKB max:%sKB ", runtime.freeMemory() * 100f / runtime.totalMemory(),
runtime.freeMemory(), runtime.totalMemory() / 1024, runtime.maxMemory() / 1024);
msg += String.format("native: free:%sKB total:%sKB max:%sKB", android.os.Debug.getNativeHeapFreeSize() / 1024,
android.os.Debug.getNativeHeapAllocatedSize() / 1024, android.os.Debug.getNativeHeapSize() / 1024);
msg += String.format("| availMem:%sKB", memoryInfo.availMem / 1024);
Log.d("memory", msg);
}
};
mTimer = new Timer();
mTimer.schedule(mTimerTask, 1000, 1000);
}
public void updateAllowState() {
// We fail safe and prevent disabling keyguard in the unlikely event this gets
// called before DevicePolicyManagerService has started.
DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(
Context.DEVICE_POLICY_SERVICE);
if (dpm != null) {
try {
mAllowDisableKeyguard = dpm.getPasswordQuality(null,
ActivityManager.getService().getCurrentUser().id)
== DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED ?
ALLOW_DISABLE_YES : ALLOW_DISABLE_NO;
} catch (RemoteException re) {
// Nothing much we can do
}
}
}
public boolean isAppOnForeground() {
// Returns a list of application processes that are running on the
// device
String packageName = context.getPackageName();
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null)
return false;
for (RunningAppProcessInfo appProcess : appProcesses) {
// importance:
// The relative importance level that the system places
// on this process.
// May be one of IMPORTANCE_FOREGROUND, IMPORTANCE_VISIBLE,
// IMPORTANCE_SERVICE, IMPORTANCE_BACKGROUND, or IMPORTANCE_EMPTY.
// These constants are numbered so that "more important" values are
// always smaller than "less important" values.
// processName:
// The name of the process that this object is associated with.
if (appProcess.processName.equals(packageName) && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;
}
private void initGlSurfaceView() {
mGLSurfaceView = new StarWarsTilesGLSurfaceView(getContext());
mGLSurfaceView.setBackgroundColor(Color.TRANSPARENT);
// Check if the system supports OpenGL ES 2.0.
final ActivityManager activityManager = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000;
if (supportsEs2) {
// Request an OpenGL ES 2.0 compatible context.
mGLSurfaceView.setEGLContextClientVersion(2);
mRenderer = new StarWarsRenderer(mGLSurfaceView, this, mAnimationDuration, mNumberOfTilesX);
mGLSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
mGLSurfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT);
mGLSurfaceView.setRenderer(mRenderer);
mGLSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
mGLSurfaceView.setZOrderOnTop(true);
} else {
throw new UnsupportedOperationException();
}
}
public VideoLoadAsync(Fragment fragment, ImageView imageView, boolean isScrolling, int width) {
mImageView = imageView;
this.fragment = fragment;
mWidth = width;
mIsScrolling = isScrolling;
final int memClass = ((ActivityManager) fragment.getActivity().getSystemService(Context.ACTIVITY_SERVICE))
.getMemoryClass();
final int size = 1024 * 1024 * memClass / 8;
// Handle orientation change.
GalleryRetainCache c = GalleryRetainCache.getOrCreateRetainableCache();
mCache = c.mRetainedCache;
if (mCache == null) {
// The maximum bitmap pixels allowed in respective direction.
// If exceeding, the cache will automatically scale the
// bitmaps.
/* final int MAX_PIXELS_WIDTH = 100;
final int MAX_PIXELS_HEIGHT = 100;*/
mCache = new GalleryCache(size, mWidth, mWidth);
c.mRetainedCache = mCache;
}
}
@Override
public List<Entry> getTasksFromRecents(boolean isIncognito) {
Context context = ContextUtils.getApplicationContext();
ActivityManager activityManager =
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<Entry> entries = new ArrayList<Entry>();
for (ActivityManager.AppTask task : activityManager.getAppTasks()) {
Intent intent = DocumentUtils.getBaseIntentFromTask(task);
if (!isValidActivity(isIncognito, intent)) continue;
int tabId = getTabIdFromIntent(intent);
if (tabId == Tab.INVALID_TAB_ID) continue;
String initialUrl = getInitialUrlForDocument(intent);
entries.add(new Entry(tabId, initialUrl));
}
return entries;
}
/**
* 判断进程是否存活
*/
public static boolean isProcessLive(@NonNull Context context, @NonNull String processName) {
if (TextUtils.isEmpty(processName)) {
return false;
}
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (am == null) {
return false;
}
List<ActivityManager.RunningAppProcessInfo> list = am.getRunningAppProcesses();
if (list == null) {
return false;
}
for(ActivityManager.RunningAppProcessInfo info : list){
if(processName.equals(info.processName)){
return true;
}
}
return false;
}
public static boolean isMainProcess(Context context) {
try {
ActivityManager am = ((ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE));
List<ActivityManager.RunningAppProcessInfo> processInfo = am.getRunningAppProcesses();
String mainProcessName = context.getPackageName();
int myPid = android.os.Process.myPid();
for (ActivityManager.RunningAppProcessInfo info : processInfo) {
if (info.pid == myPid && mainProcessName.equals(info.processName)) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 获取当前进程的进程名
*
* @param context
* @return
*/
private static String getCurProcessName(Context context) {
int pid = Process.myPid();
ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}
private void startUniversalCopy(){
Log.e(TAG,"startUniversalCopy");
Activity topActivity=null;
ActivityManager activityManager= (ActivityManager) mActivities.get(0).getApplication().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfos=activityManager.getRunningTasks(1);
if (taskInfos.size()>0){
ComponentName top=taskInfos.get(0).topActivity;
if (top!=null){
String name=top.getClassName();
for (Activity activity:mActivities){
if (activity.getClass().getName().equals(name)){
topActivity=activity;
break;
}
}
}
}
if (topActivity==null){
if (mActivities.size()>0) {
topActivity = mActivities.get(mActivities.size() - 1);
if (topActivity.isFinishing()){
topActivity=null;
}
}
}
UniversalCopy(topActivity);
}
private boolean isRunning(Class<?> serviceClass) {
ActivityManager mgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : mgr.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private void sendConfigurationLocked() {
if (mSetUiMode != mConfiguration.uiMode) {
mSetUiMode = mConfiguration.uiMode;
try {
ActivityManager.getService().updateConfiguration(mConfiguration);
} catch (RemoteException e) {
Slog.w(TAG, "Failure communicating with activity manager", e);
}
}
}
private void reopenActivity() throws InterruptedException {
final Context context = instrumentation.getContext();
@SuppressWarnings("deprecation")
final Intent intent = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
.getRecentTasks(2, 0).get(1).baseIntent;
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
instrumentation.getContext().startActivity(intent);
Thread.sleep(WAIT_REOPEN_ACTIVITY);
}
void updateUidState(int uid, int procState) {
synchronized (mLock) {
if (procState == ActivityManager.PROCESS_STATE_TOP) {
// Only use this if we are exactly the top app. All others can live
// with just the foreground priority. This means that persistent processes
// can never be the top app priority... that is fine.
mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
} else if (procState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_APP);
} else {
mUidPriorityOverride.delete(uid);
}
}
}