I have a application 'A' and application 'B'.
Say, I have a string resource in the application 'A'
<\string name="abc">ABCDEF<\/string>
How do I access the value of abc from the Activity in 'B'.
I tried the following method.
try {
PackageManager pm = getPackageManager();
ComponentName component = new ComponentName(
"com.android.myhome",
"com.android.myhome.WebPortalActivity");
ActivityInfo activityInfo = pm.getActivityInfo(component, 0);
Resources res = pm.getResourcesForApplication(activityInfo.applicationInfo);
int resId = res.getIdentifier("abc", "string", null);
}
catch(NameNotFoundException e){
}
Always resId is returned 0 always.. Can anyone please let me know if I could access string abc from the application 'B'
Regards,
SANAT
It is possible! Take a look at the following code. It works for me.
public void testUseAndroidString() {
Context context = getContext();
Resources res = null;
try {
//I want to use the clear_activities string in Package com.android.settings
res = context.getPackageManager().getResourcesForApplication("com.android.settings");
int resourceId = res.getIdentifier("com.android.settings:string/clear_activities", null, null);
if(0 != resourceId) {
CharSequence s = context.getPackageManager().getText("com.android.settings", resourceId, null);
Log.i(VIEW_LOG_TAG, "resource=" + s);
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
Hope this will help you.
It seems Ok. Here is my code
Resources res = null;
try {
res = getPackageManager().getResourcesForApplication("com.sjm.testres1");
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(null != res) {
int sId = res.getIdentifier("com.sjm.testres1:string/app_name1", null, null);
int dId = res.getIdentifier("com.sjm.testres1:drawable/card_1_big", null, null);
if(0 != dId) {
iv.setBackgroundDrawable(res.getDrawable(dId));
}
if(0 != sId) {
tv.setText(res.getString(sId));
}
}
Related
ResourceNotFound exception in 6.0 and below..am trying to access drawable from another application. In my ccase i would like to apply theme from another application. For example launcher app.
Method:1
try {
String mDrawableName = "icon";
Resources mApk1Resources = manager.getResourcesForApplication(package_name);
int mDrawableResID = mApk1Resources.getIdentifier("icon", "drawable", package_name);
Drawable myDrawable = mApk1Resources.getDrawable(mDrawableResID);
if (myDrawable != null) {
data.add(new DataModel("" + app_name, myDrawable, package_name));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Method:2
try
{
Context otherAppContext = getActivity().createPackageContext(""+package_name, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
Resources mApk1Resources = otherAppContext.getResources();
int mDrawableResID = mApk1Resources.getIdentifier(package_name+":drawable/icon", "drawable", package_name);
Drawable myDrawable = mApk1Resources.getDrawable(mDrawableResID);
if (myDrawable != null) {
data.add(new DataModel("" + app_name, myDrawable, package_name));
}
}
catch(Exception e)
{
e.printStackTrace();
}
I want to add an option in my file manager to show the App Icons of a directory. The code below didn't work; what did I do wrong?
ImageView icon;
private static Activity activity;
String temp = mFileMang.getCurrentDir();
} else if (sub_ext.equalsIgnoreCase("apk")) {
final Drawable appicon;
try {
PackageInfo packageInfo = activity.getPackageManager()
.getPackageArchiveInfo(temp,
PackageManager.GET_ACTIVITIES);
ApplicationInfo appInfo = packageInfo.applicationInfo;
appInfo.sourceDir = temp;
appInfo.publicSourceDir = temp;
appicon = appInfo
.loadIcon(activity.getPackageManager());
mViewHolder.icon.setImageDrawable(appicon);
} catch (Exception e) {
mViewHolder.icon.setImageResource(R.drawable.appicon);
}
try this.. i fetch the icon from the sd card directory ..icon from the apk files which are not installed ...
public class A extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_listing);
ListView list = (ListView) findViewById(R.id.app_listing);
ArrayList<PackageInfoStruct> listData = getApks();
list.setAdapter(new TestAdapter(listData, A.this));
}
class PackageInfoStruct {
String appname = "";
String pname = "";
String versionName = "";
int versionCode = 0;
Drawable icon;
String datadir = "";
}
public ArrayList<PackageInfoStruct> res;
private ArrayList<PackageInfoStruct> getApks() {
try {
String path = Environment.getExternalStorageDirectory() + "/test";
File file = new File(path);
String[] list = file.list();
res = new ArrayList<PackageInfoStruct>();
for (String str : list) {
String not_installed_apk_file = path + "/" + str;
PackageManager pm = getPackageManager();
PackageInfo pi = pm.getPackageArchiveInfo(
not_installed_apk_file, 0);
if (pi == null)
continue;
// the secret are these two lines....
pi.applicationInfo.sourceDir = not_installed_apk_file;
pi.applicationInfo.publicSourceDir = not_installed_apk_file;
//
Drawable APKicon = pi.applicationInfo.loadIcon(pm);
String AppName = (String) pi.applicationInfo.loadLabel(pm);
PackageInfoStruct pack = new PackageInfoStruct();
pack.icon = APKicon;
pack.pname = AppName;
res.add(pack);
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
private ArrayList<PackageInfoStruct> getInstalledApps() {
try {
res = new ArrayList<PackageInfoStruct>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(
0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
PackageInfoStruct newInfo = new PackageInfoStruct();
newInfo.appname = p.applicationInfo.loadLabel(
getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.datadir = p.applicationInfo.dataDir;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(this
.getPackageManager());
res.add(newInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
}
PackageManager..getPackageArchiveInfo(..) method will work only for installed apks, means it will operate only on an apk file, which has already been installed. Currently you maybe checking this on an apk file, which might not be installed and thus getting package info is failed.
What you can do is:
Unzip the apk file programatically (Basically apk file is a zip file, and you can extract it programatically. see http://www.jondev.net/articles/Unzipping_Files_with_Android_(Programmatically) )
Get the AndroidManifest.xml file from the zip entry
Parse the AndroidManifest.xml file ( see How to parse the AndroidManifest.xml file inside an .apk package )
Get the xml attribute 'android:icon' from it
Read the icon file from the zip entry again as bitmap.
use this icon bitmap wherever you want.
Just Try with this-
ImageView icon;
private static Activity activity;
String temp = mFileMang.getCurrentDir();
} else if (sub_ext.equalsIgnoreCase("apk")) {
final Drawable appicon;
try {
PackageInfo packageInfo = activity.getPackageManager()
.getPackageArchiveInfo(temp,
PackageManager.GET_ACTIVITIES);
ApplicationInfo appInfo = packageInfo.applicationInfo;
appInfo.sourceDir = temp;
appInfo.publicSourceDir = temp;
PackageManager pm = getPackageManager();
appicon = pm.getApplicationIcon(appInfo.packageName);
mViewHolder.icon.setImageDrawable(appicon);
} catch (Exception e) {
mViewHolder.icon.setImageResource(R.drawable.appicon);
}
to add this http://stackoverflow.com/questions/17919151/android-app-icon-filemanager/17924795#17924795 to my code i need to cut it. finally i got this:
but when I open the directory it load only 1 icon and show it for all other apps too.
https://www.dropbox.com/s/e2bonh3fkfseggf/Screenshot_2013-07-31-13-58-18.png
File file = new File(temp + "/" + mDataSource.get(position));
} else if (sub_ext.equalsIgnoreCase("apk")) {
try {
Drawable icon = getApk(file);
mViewHolder.icon.setImageDrawable(icon);
} catch (Exception e) {
mViewHolder.icon.setImageResource(R.drawable.appicon);
}
private Drawable getApk(File file2) {
try {
String path = mFileMang.getCurrentDir();
File file = new File(path);
String[] list = file.list();
for (String str : list) {
String not_installed_apk_file = path + "/" + str;
PackageManager pm = mContext.getPackageManager();
PackageInfo pi = pm.getPackageArchiveInfo(
not_installed_apk_file, 0);
if (pi == null)
continue;
// the secret are these two lines....
pi.applicationInfo.sourceDir = not_installed_apk_file;
pi.applicationInfo.publicSourceDir = not_installed_apk_file;
//
res = pi.applicationInfo.loadIcon(pm);
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
PackageManager pm = context.getPackageManager();
PackageInfo info =pm.getPackageArchiveInfo(apkPath,PackageManager.GET_ACTIVITIES);
I downloaded a class from Catch The Cows, it is akin to a Google Map object or at least that is what I am using it for.
It parses an XML file which lists the areas of the screen that should be touchable, and then creates them with this method.
This is here for context, I have commented out some parts of code, and added my own to try and resolve my issue
private Area addShape( String shape, String name, String coords, String id) {
Log.v("IDS:", "id was "+id);
Area a = null;
String rid = id.replace("#+id/", "");
Log.v("IDS:", "rid was "+rid);
// Generate a new ID for the area.
int _id = 1;
View vi = findViewById(_id);
while (vi!=null) {
_id++;
vi = findViewById(_id);
}
//View.generateViewId(); //=0;
Log.v("IDS:", "After conversion final time "+_id);
/*
try {
Class<R.id> res = R.id.class;
Field field = res.getField(rid); // eg. rid = area10
_id = field.getInt(null);
Log.v("IDS:", "After conversion "+_id);
}
catch (Exception e) {
_id = 0;
Log.e("Exception ",e.getMessage());
} finally {
Log.v("IDS:", "After conversion final time "+_id);
}
*/
if (_id != 0) {
if (shape.equalsIgnoreCase("rect")) {
String[] v = coords.split(",");
if (v.length == 4) {
a = new RectArea(_id, name, Float.parseFloat(v[0]),
Float.parseFloat(v[1]),
Float.parseFloat(v[2]),
Float.parseFloat(v[3]));
}
}
if (shape.equalsIgnoreCase("circle")) {
String[] v = coords.split(",");
if (v.length == 3) {
a = new CircleArea(_id,name, Float.parseFloat(v[0]),
Float.parseFloat(v[1]),
Float.parseFloat(v[2])
);
}
}
if (shape.equalsIgnoreCase("poly")) {
a = new PolyArea(_id,name, coords);
}
if (a != null) {
addArea(a);
}
} else {
Log.v("Loading ID: ","_id was 0");
}
return a;
}
Unfortunately nothing was rendering on the screen, and this was because _id = 0. This should be changed with this bit of code:
try {
Class<R.id> res = R.id.class;
Field field = res.getField(rid); // eg. rid = area10
_id = field.getInt(null);
}
How ever I am not sure what it does to try and debug it, can anyone explain what this snippet is doing?
R is a Read-Only class. It is generate at compile time and You should not use reflection to modify its field. Also you should avoid reflection to access the fields values. You should use the official API.
The comment at the first row of the class is
/* AUTO-GENERATED FILE. DO NOT MODIFY. */
I want to know the exact functionality of Intent.ACTION_PRE_BOOT_COMPLETED. Currently, my requirement is to complete the task before the completion of booting of the device, i.e. before the call of Intent.ACTION_BOOT_COMPLETED.
Can anyone guide me on how to proceed to fulfill the requirement? Any help in this regard will be well appreciated.
ACTION_PRE_BOOT_COMPLETED is sended in ActivityManagerService.java::systemReady.
But to received it, the uid of your application must be system(1000).
for (int i=ris.size()-1; i>=0; i--) {
if ((ris.get(i).activityInfo.applicationInfo.flags
&ApplicationInfo.FLAG_SYSTEM) == 0) {
ris.remove(i);
}
}
Further more, this broadcast could only be received once in each upgrade( not very sure here, maybe should be each wipe data).
Note code below, if the target is in lastDoneReceivers, it will be removed.
ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
for (int i=0; i<ris.size(); i++) {
ActivityInfo ai = ris.get(i).activityInfo;
ComponentName comp = new ComponentName(ai.packageName, ai.name);
if (lastDoneReceivers.contains(comp)) {
ris.remove(i);
i--;
}
}
lastDoneReceivers is read from file /data/system/called_pre_boots.dat.
private static File getCalledPreBootReceiversFile() {
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system");
File fname = new File(systemDir, "called_pre_boots.dat");
return fname;
}
static final int LAST_DONE_VERSION = 10000;
private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
File file = getCalledPreBootReceiversFile();
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
int fvers = dis.readInt();
if (fvers == LAST_DONE_VERSION) {
String vers = dis.readUTF();
String codename = dis.readUTF();
String build = dis.readUTF();
if (android.os.Build.VERSION.RELEASE.equals(vers)
&& android.os.Build.VERSION.CODENAME.equals(codename)
&& android.os.Build.VERSION.INCREMENTAL.equals(build)) {
int num = dis.readInt();
while (num > 0) {
num--;
String pkg = dis.readUTF();
String cls = dis.readUTF();
lastDoneReceivers.add(new ComponentName(pkg, cls));
}
}
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
}
}
}
return lastDoneReceivers;
}
There is no such action as ACTION_PRE_BOOT_COMPLETED. I think that you normally can't fill your requirement. May be there is some mechanism for system signed apps to do that.
I want to get icons of my all installed apps. Can I get that icons using package manager? Is there any function for it? Or any other way to get icons of all installed apps in bitmap?
Thanks!
try {
String pkg = "com.app.my";//your package name
Drawable icon = getContext().getPackageManager().getApplicationIcon(pkg);
imageView.setImageDrawable(icon);
} catch (PackageManager.NameNotFoundException ne) {
}
Check here for more details.
Above answers are pretty good.
Your Question is:- Get icons of all installed apps in android?
you want list of install apps icon
Here is the code which help you to get install apps list with Application (icons,packages names).
**Declare variable in your Activity**
private CustomAppListAdapter customAppListAdapter;
private ArrayList<AppListMain> appListMainArrayList;
private AppListMain appListMain;
Just call below function loadApps() in your Activity onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_list);
loadApps();
}
public void loadApps() {
try {
packageManager = getPackageManager();
appListMainArrayList = new ArrayList<>();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfoList) {
AppListMain appListMain = new AppListMain();
appListMain.setAppIcon(resolveInfo.activityInfo.loadIcon(packageManager));
appListMain.setAppName(resolveInfo.loadLabel(packageManager).toString());
appListMain.setAppPackage(resolveInfo.activityInfo.packageName);
appListMainArrayList.add(appListMain);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is Link for reference
OR
You can download custom launcher code from My Github repository
I find it the easiest way:
private List<ResolveInfo> installedApps() {
final Intent main_intent = new Intent(Intent.ACTION_MAIN, null);
main_intent.addCategory(Intent.CATEGORY_LAUNCHER);
return package_manager.queryIntentActivities(main_intent, 0);
}
Now to get the icons, use this:
for(ResolveInfo ri : installedApps()) {
// to get drawable icon --> ri.loadIcon(package_manager)
}
Try this way: Make a class called PackageInformation:
public class PackageInformation {
private Context mContext;
public PackageInformation(Context context) {
mContext = context;
}
class InfoObject {
public String appname = "";
public String pname = "";
public String versionName = "";
public int versionCode = 0;
public Drawable icon;
public void InfoObjectAggregatePrint() { //not used yet
Log.v(appname, appname + "\t" + pname + "\t" + versionName + "\t" + versionCode);
}
}
private ArrayList < InfoObject > getPackages() {
ArrayList < InfoObject > apps = getInstalledApps(false);
final int max = apps.size();
for (int i = 0; i < max; i++) {
apps.get(i).prettyPrint();
}
return apps;
}
public ArrayList < InfoObject > getInstalledApps(boolean getSysPackages) {
ArrayList < InfoObject > res = new ArrayList < InfoObject > ();
List < PackageInfo > packs = mContext.getPackageManager().getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue;
}
InfoObject newInfo = new InfoObject();
newInfo.appname = p.applicationInfo.loadLabel(mContext.getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(mContext.getPackageManager());
res.add(newInfo);
}
return res;
}
}
tuck this away somewhere and now to access the info from your working Activity class do this:
PackageInformation androidPackagesInfo = new PackageInformation(this);
ArrayList < InfoObject > appsData = androidPackagesInfo.getInstalledApps(true);
for (InfoObject info: appsData) {
Toast.makeText(MainActivity.this, info.appname, 2).show();
Drawable somedrawable = info.icon;
}
Here below is the code with which you can get the icons of all installed Apps.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
// try getting the properly colored launcher icons
LauncherApps launcher = (LauncherApps) this.getSystemService(LAUNCHER_APPS_SERVICE);
List<LauncherActivityInfo> activityList = launcher.getActivityList(packageName, android.os.Process.myUserHandle());
drawable = activityList.get(0).getBadgedIcon(0);
} catch (Exception e) {
}
}
if (drawable == null) {
try {
getPackageManager().getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}