⑴ android怎麼獲取一個包下的全部類名
您好,我在別的論壇也看到您的問題,很高興為您解答:
/**
* 從包package中獲取所有的Class
*
* @param pack
* @return
*/
public static Set<Class<?>> getClasses(Package pack) {
// 第一個class類的集合
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
// 是否循環迭代
boolean recursive = true;
// 獲取包的名字 並進行替換
String packageName = pack.getName();
String packageDirName = packageName.replace('.', '/');
// 定義一個枚舉的集合 並進行循環來處理這個目錄下的things
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(
packageDirName);
// 循環迭代下去
while (dirs.hasMoreElements()) {
// 獲取下一個元素
URL url = dirs.nextElement();
// 得到協議的名稱
String protocol = url.getProtocol();
// 如果是以文件的形式保存在伺服器上
if ("file".equals(protocol)) {
// 獲取包的物理路徑
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式掃描整個包下的文件 並添加到集合中
(packageName, filePath,
recursive, classes);
} else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定義一個JarFile
JarFile jar;
try {
// 獲取jar
jar = ((JarURLConnection) url.openConnection())
.getJarFile();
// 從此jar包 得到一個枚舉類
Enumeration<JarEntry> entries = jar.entries();
// 同樣的進行循環迭代
while (entries.hasMoreElements()) {
// 獲取jar里的一個實體 可以是目錄 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/開頭的
if (name.charAt(0) == '/') {
// 獲取後面的字元串
name = name.substring(1);
}
// 如果前半部分和定義的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"結尾 是一個包
if (idx != -1) {
// 獲取包名 把"/"替換成"."
packageName = name.substring(0, idx)
.replace('/', '.');
}
// 如果可以迭代下去 並且是一個包
if ((idx != -1) || recursive) {
// 如果是一個.class文件 而且不是目錄
if (name.endsWith(".class")
&& !entry.isDirectory()) {
// 去掉後面的".class" 獲取真正的類名
String className = name.substring(
packageName.length() + 1, name
.length() - 6);
try {
// 添加到classes
classes.add(Class
.forName(packageName + '.'
+ className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes; }
/**
* 以文件的形式來獲取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
public static void (String packageName,
String packagePath, final boolean recursive, Set<Class<?>> classes) {
// 獲取此包的目錄 建立一個File
File dir = new File(packagePath);
// 如果不存在或者 也不是目錄就直接返回
if (!dir.exists() || !dir.isDirectory()) {
return;
}
// 如果存在 就獲取包下的所有文件 包括目錄
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定義過濾規則 如果可以循環(包含子目錄) 或則是以.class結尾的文件(編譯好的java類文件)
public boolean accept(File file) {
return (recursive && file.isDirectory())
|| (file.getName().endsWith(".class"));
}
});
// 循環所有文件
for (File file : dirfiles) {
// 如果是目錄 則繼續掃描
if (file.isDirectory()) {
(packageName + "."
+ file.getName(), file.getAbsolutePath(), recursive,
classes);
} else {
// 如果是java類文件 去掉後面的.class 只留下類名
String className = file.getName().substring(0,
file.getName().length() - 6);
try {
// 添加到集合中去
classes.add(Class.forName(packageName + '.' + className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
轉載,僅供參考。
如果我的回答沒能幫助您,請繼續追問。
⑵ 如何解析從Android的一個字元串的URL
需要根據URL地址獲取圖片載入到圖中Anroid機器人所在的位置,這是運行前的效果
首先需根據URL地址獲取圖片,如下所示,urladdr即為圖片地址,返回Drawable對象:
//download image from network using @urladdress
private Drawable loadImageFromNetwork(String urladdr) {
// TODO Auto-generated method stub
Drawable drawable = null;
try{
//judge if has picture locate or not according to filename
drawable = Drawable.createFromStream(new URL(urladdr).openStream(), "image.jpg");
}catch(IOException e){
Log.d("test",e.getMessage());
}
if(drawable == null){
Log.d("test","null drawable");
}else
Log.d("test","not null drawable");
}
return drawable;
}
獲取到圖片後,需要更新主線程UI資源,考慮到時間以及界面反應延遲等,所以採用線程加以處理,如下圖所示:
// image
new Thread(new Runnable(){
Drawable drawable = loadImageFromNetwork(urladdress);
@Override
public void run(){
//post() is quite important,update pictures in UI main thread
image.post(new Runnable(){
@Override
public void run(){
//TODO Auto-generated method stub
image.setImageDrawable(drawable);
}
});
}
//download image from network using @urladdress
private Drawable loadImageFromNetwork(String urladdr) {
//... 略(如 1 中所示)
}
}).start(); //線程啟動
4.說明:在上述示例代碼中,image是ImageView類的一個對象,也就是APP中的一個顯示圖像組件,利用獲取到的圖片drawable去更新image,
⑶ android怎麼從sd卡指定的文件夾中獲取所有圖片的路徑URL,謝謝~感謝各位大神了
直接調用文件管理器選擇圖片即可。
1、調用系統提供的圖片選擇器,代碼如下:
//注意,在Android4.4系統下建議使用 Intent.ACTION_OPEN_DOCUMENT方式
if (Utility.isKK()) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
處理返回結果:
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case PIC_RESULT://選擇圖庫
case PIC_RESULT_KK:
imageFileUri = intent.getData();//獲取選擇圖片的URI
break;
}
}
2、除此自外,系統還提供一種選擇器,這個圖片選擇器可以屏蔽掉那個auto backup的目錄.所以就開始打算用這個圖片選擇器來選圖片了.
Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/jpeg");
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){
startActivityForResult(intent, SELECT_PIC_KITKAT);
}else{
startActivityForResult(intent, SELECT_PIC);
}
為什麼要分開不同版本呢?其實在4.3或以下可以直接用ACTION_GET_CONTENT的,在4.4或以上,官方建議用ACTION_OPEN_DOCUMENT,主要區別是他們返回的Uri.4.3返回的是帶文件路徑的,而4.4返回的卻是content://com.android.providers.media.documents/document/image:3951這樣的,沒有路徑,只有圖片編號的uri.可以通過以下方式,處理URI。
參考:Android 4.4從圖庫選擇圖片,獲取圖片路徑並裁剪
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
3、使用其它開源組件如PhotoView。
⑷ 安卓手機怎麼打開url
安卓手機打開url文件首先需要在文件管理器中找到需要打開的url文件,再用「文本」方式打開,點擊使用HTML查看器打開。最底下一行是網路地址,從「=」號後面開始選擇,直接復制,打開瀏覽器在瀏覽器搜索欄中粘貼url,點擊進入即可看到相關內容。
在WWW上,每一信息資源都有統一的且在網上唯一的地址,該地址就叫URL(Uniform Resource Locator,統一資源定位器),它是WWW的統一資源定位標志,就是指網路地址。
相關信息
hostname(主機名)
是指存放資源的伺服器的域名系統(DNS)主機名或IP地址。有時,在主機名前也可以包含連接到伺服器所需的用戶名和密碼(格式:username:password@hostname)。
port(埠號)
整數,可選,省略時使用方案的默認埠,各種傳輸協議都有默認的埠號,如http的默認埠為80。如果輸入時省略,則使用默認埠號。有時候出於安全或其他考慮,可以在伺服器上對埠進行重定義,即採用非標准埠號,此時,URL中就不能省略埠號這一項。
⑸ android 使用URL獲取本地的文件
public String getFromAssets(String fileName){
try {
InputStreamReader inputReader = new InputStreamReader( getResources().getAssets().open(fileName) );
BufferedReader bufReader = new BufferedReader(inputReader);
String line="";
String Result="";
while((line = bufReader.readLine()) != null)
Result += line;
return Result;
} catch (Exception e) {
e.printStackTrace();
}
}
⑹ Android:URL參數獲取和修改
項目中使用混合開發,很多地方都會用到url,需要傳參、拼接、修改參數,小記一下;
⑺ android手機怎麼才能直接打開URL鏈接文件
在安卓代碼中調用瀏覽器來打開相應的網頁,一般有以下幾種方式
調用默認瀏覽器。
其他瀏覽器。
自定義一個簡單的WebView瀏覽器。
【原理】
主要是通過代碼進行調用已有或者未有的瀏覽器進行打開相應的網頁進行瀏覽。
【詳細實現步奏】
一.調用默認瀏覽器
優缺點:部分手機可能連默認的瀏覽器都沒有。
123456二.其他瀏覽器,制定打開
缺點:必須知道打開的瀏覽器的包名,大部分用戶可能沒有安裝這些瀏覽器
123456三.自定義一個簡單的WebView瀏覽器
優缺點:推薦使用,不必擔心手機上是否有瀏覽器。
12345【最後】
每種方法根據個人需要進行選用,沒其他特別因素推薦使用第三種方案。