android - 关于判断activity是否存在
天蓬老师
天蓬老师 2017-04-17 17:56:38
0
4
573

各位,我用这个方法在
判断activity是否存在,
我把红色的的类名改成KoBe,但是还是显示这个activity存在;但是你看

KoBe是不存在这个包里的,请问这是咋回事????

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(4)
巴扎黑

It’s time to give up this method. I don’t know how many people this method has harmed. Let’s take a look at the Intent source code

As other respondents said, there is no verification of the component, so no matter what setClassName parameter you set, the returned ComponentName must not be empty, so there is always a problem with the activity mentioned by the questioner.
Solution, use another method

Intent intent = new Intent();
intent.setClassName(getPackageName(), "xxx.xxx.XxxActivity");
ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
if(resolveInfo != null) {
     //activity found
}else{
     //activity not found
}

Note that the second parameter of setClassName is 包名+类名

洪涛
try {
    startActivity(new Intent(..));
} catch (ActivityNotFoundException e) {
    Toast.makeText(this, "Not installed.", LENGTH_SHORT).show();
}

This method is the simplest and crudest

迷茫
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> list = am.getRunningTasks(100);
boolean isAppRunning = false;
String MY_PKG_NAME = "xx.xx.xx";
for (RunningTaskInfo info : list) {
    if (info.topActivity.getPackageName().equals(MY_PKG_NAME) || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
        isAppRunning = true;
        
        break;
    }
}

You can use ActivityManager to judge

迷茫

resolveActivity simply returns the value set by setClassName
There is no verification of whether the class exists.
If it is in the same process, it is recommended to use Class.forName(className) to detect whether the class exists

public Intent setClassName(String packageName, String className) {
    mComponent = new ComponentName(packageName, className);
    return this;
}
public ComponentName resolveActivity(PackageManager pm) {
    if (mComponent != null) {
        return mComponent;
    }
    ...
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template