一.获取当前运行app的包名(包括第三方)
/*
•注意:getRunningAppProcesses0 方法在5.0开始,就只返回自身应用的进程,所以只能判断自身进程状态,
•如果是400,返回为null,不能拿到当前栈顶Activty的包名
* @param context
* @return
*/
//能获取到当前的包名
private static String getCurrentPkgName(Context context) {
// 5x系统以后利用反射获取当前栈顶activity的包名。
ActivityManager.RunningAppProcessInfo currentinfo = null;
Field field = null;
int startTaskToFront = 2;
String pkgName = null;
try {
//通过反射获取进程状态字段
field = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");
} catch (Exception e) {
e.printStackTrace();
}
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List appList = am.getRunningAppProcesses();
ActivityManager.RunningAppProcessInfo app;
for (int i = 0; i < appList.size(); i++) {
//ActivityManager.RunningAppProcessInfoapp:appList
app = (ActivityManager.RunningAppProcessInfo) appList.get(i);
//表示前台运行进程•
if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
Integer state = null;
try {
//反射调用字段值的方法,获取该进程的状态。
state = field.getInt(app);
} catch (Exception e) {
e.printStackTrace();
}
//根据这个判断条件从前台获取当初切换的对象
if (state != null && state == startTaskToFront) {
currentinfo = app;
break;
}
}
}
if (currentinfo != null) {
pkgName = currentinfo.processName;
}
Log.e(DEBUG_TAG, "pkgname = " + pkgName);
return pkgName;
}
二、获取当前运行的类名
//能过获取到当前运行的类
private String getActivities(Activity activity,String packageName)
{
String mActivity = null;
Intent localIntent = new Intent("android.intent.action.MAIN", null);
localIntent.addCategory("android.intent.category.LAUNCHER");
List<ResolveInfo> appList = activity.getPackageManager().queryIntentActivities(localIntent, 0);
for (int i = 0; i < appList.size(); i++) {
ResolveInfo resolveInfo = appList.get(i);
String packageStr = resolveInfo.activityInfo.packageName;
if (packageStr.equals(packageName)) {
//这个就是你想要的那个Activity
android.util.Log.e("", "" + resolveInfo.activityInfo.name);
mActivity = resolveInfo.activityInfo.name;
break;
}
}
return mActivity;
}
三、往当前焦点送数据
View rootview = getWindow().getDecorView();
View aaa = rootview.findFocus();
if (aaa != null) {
Message msg = new Message();
msg.what = 1;
msg.arg1 = aaa.getId();
msg.obj = "abcde";
handler.sendMessage(msg);
Log.e(DEBUG_TAG, aaa.toString() + "id:" + Integer.toString(msg.arg1));
}
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what)
{
case 1:
textView = (TextView) findViewById(msg.arg1);
if (textView != null) {
textView.setText(msg.obj.toString());
}
Log.e(DEBUG_TAG, "Set test abcdef!!!!");
break;
}
}
};
四.获取当前运行的Activity据说该种方法目前只适用安卓4.0以前的,但是我在公司设备的5.1.1上能够获取本app的activity
public static Activity getActivity() {
Class activityThreadClass = null;
try {
activityThreadClass = Class.forName("android.app.ActivityThread");
Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
activitiesField.setAccessible(true);
Map activities = (Map) activitiesField.get(activityThread);
for (Object activityRecord : activities.values()) {
Class activityRecordClass = activityRecord.getClass();
Field pausedField = activityRecordClass.getDeclaredField("paused");
pausedField.setAccessible(true);
if (!pausedField.getBoolean(activityRecord)) {
Field activityField = activityRecordClass.getDeclaredField("activity");
activityField.setAccessible(true);
Activity activity = (Activity) activityField.get(activityRecord);
return activity;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
五,基于四的问题更高版本的and建议使用registerActivityLifecycleCallbacks来监听activity的生命周期
1.首先创建管理类
package com.example.getforcus;
import android.app.Activity;
import java.lang.ref.WeakReference;
public class TestActivityManager {
private static TestActivityManager sInstance = new TestActivityManager();
private WeakReference<Activity> sCurrentActivityWeakRef;
private TestActivityManager() {
}
public static TestActivityManager getInstance() {
return sInstance;
}
public Activity getCurrentActivity() {
Activity currentActivity = null;
if (sCurrentActivityWeakRef != null) {
currentActivity = sCurrentActivityWeakRef.get();
}
return currentActivity;
}
public void setCurrentActivity(Activity activity) {
sCurrentActivityWeakRef = new WeakReference<Activity>(activity);
}
}
2.创建对应的回调实现函数registerActivityLifecycleCallbacks
package com.example.getforcus;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class MyApplication extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
TestActivityManager.getInstance().setCurrentActivity(activity);
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
}
public static Context getContext() {
return context;
}
}
3.在需要引用的app的AndroiManifest.xml中加入android:name=".MyApplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.GetForcus"
android:name=".MyApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
4.使用范例
@Override
protected void onResume() {
super.onResume();
Log.e(DEBUG_TAG, "onResume()");
MyApplication myApplication = new MyApplication();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
View rootview = TestActivityManager.getInstance().getCurrentActivity().getWindow().getDecorView();
View aaa = rootview.findFocus();
if (aaa != null) {
Message msg = new Message();
msg.what = 1;
msg.arg1 = aaa.getId();
msg.obj = "abcde";
handler.sendMessage(msg);
Log.e(DEBUG_TAG, aaa.toString() + "id:" + Integer.toString(msg.arg1));
}
}
}
}).start();
}