在我的情况下,我知道以下一些方法
getApplicationContext().getResources().getIdentifier("nameOfDrawable", "drawable", packageName);
getApplicationContext().getPackageManager().getApplicationIcon(packageName);
我想获取应用程序图标的可绘制ID,但是我不知道应用程序图标的“ nameOfDrawable”。我说我不知道,因为默认应用程序图标的名称可以是“ ic_launcher.png”,也可以更改为“ icon.png”之类的名称。我发现上面的第二种方法可以获取应用程序图标的drawable,但是然后我不知道该怎么办。有谁知道如何获取应用程序图标的可绘制ID?请帮忙,谢谢!
实际上,我想显示一个通知,但是它需要使用图标的可绘制ID。我发现上面的第一种方法可以获取应用程序图标的drawable ID,但是它需要应用程序图标文件的名称,该名称在不同应用程序中可以不同。我正在做的是使一个小图书馆做某事,所以无法确认某事。
最后,我找到了解决问题的方法。代码如下。
String packageName = context.getApplicationContext().getPackageName();
Intent launchIntent = context.getApplicationContext().getPackageManager().getLaunchIntentForPackage(packageName);
String className = launchIntent.getComponent().getClassName();
Class<?> c = null;
if(className != null) {
try {
c = Class.forName(className);
} catch (ClassNotFoundException e) {
Log.i(TAG, "Throw exception when try to get the main class.");
e.printStackTrace();
}
}
ApplicationInfo info = null;
try {
info = context.getApplicationContext().getPackageManager().getApplicationInfo(packageName, 0);
} catch (NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int icon = info.icon;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, null, when);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.defaults = notification.DEFAULT_SOUND|notification.DEFAULT_VIBRATE;
Intent openintent= new Intent(context, c);
PendingIntent contentIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, openintent, 0);
notification.setLatestEventInfo(context.getApplicationContext(), "Notification", message, contentIntent);
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_COUNT, notification);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句