本文实例讲述了android获取当前运行Activity名字的方法,可以避免即时聊天再出现通知的情况。分享给大家供大家参考。具体方法如下:
最近在做IM时需要知道当前Activity是哪一个Activity.自己整理一下两种方法
第一种:要方便一点(Service中无法使用)
复制代码 代码如下:
private String getRunningActivityName() {
String contextString = context.toString();
return contextString.substring(contextString.lastIndexOf(".") + 1, contextString.indexOf("@"));
}
第二种:要稍微麻烦一点,需要一个权限(推荐)
String contextString = context.toString();
return contextString.substring(contextString.lastIndexOf(".") + 1, contextString.indexOf("@"));
}
复制代码 代码如下:
<uses-permission android:name="android.permission.GET_TASKS" />
1.1.其他属性:
private String getRunningActivityName(){
ActivityManager activityManager=(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
String runningActivity=activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
return runningActivity;
}
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
RunningTaskInfo info = manager.getRunningTasks(1).get(0);String shortClassName = info.topActivity.getShortClassName(); //类名
String className = info.topActivity.getClassName(); //完整类名
String packageName = info.topActivity.getPackageName(); //包名
1.1.其他用法:
//get ActivityManagerActivityManager activityManager=(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
//one
// String className=activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
//split one by one
List<RunningTaskInfo> list=activityManager.getRunningTasks(1);
RunningTaskInfo info=list.get(0);
ComponentName componentName=info.topActivity;
String activityName=componentName.getClassName();
if(activityName!=null){
//check DeviceControlActivity is open or die
if(activityName.equals("com.android.bluetooth.DeviceControlActivity")){
//refresh DeviceControlActivity
}else{
//start DeviceControlActivity
final Intent intent = new Intent(this, DeviceControlActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
startActivity(intent);
}
}else{
//
}