From 7cf3672cd25bcd0f935ef0124144cb080dd6308d Mon Sep 17 00:00:00 2001 From: luo_dong <44437337@qq.com> Date: Wed, 1 Dec 2021 13:42:54 +0800 Subject: [PATCH 1/2] =?UTF-8?q?1.=E5=A4=84=E7=90=86=E6=89=80=E6=9C=89getEx?= =?UTF-8?q?ternalStorageDirectory=202.=E8=A7=A3=E5=86=B3=E8=B0=B7=E6=AD=8C?= =?UTF-8?q?fire=E5=BA=93build=E4=B8=8D=E8=B5=B7=E6=9D=A5=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/quseit/base/QBaseApp.java | 46 +- .../com/quseit/base/QBaseUpdateService.java | 477 +++++++++--------- .../java/com/quseit/common/CrashHandler.java | 7 +- .../com/quseit/service/DownloaderBase.java | 13 +- src/main/java/com/quseit/util/FileHelper.java | 25 +- src/main/java/com/quseit/util/FileUtils.java | 89 +++- src/main/java/com/quseit/util/Utils.java | 11 +- 7 files changed, 367 insertions(+), 301 deletions(-) diff --git a/src/main/java/com/quseit/base/QBaseApp.java b/src/main/java/com/quseit/base/QBaseApp.java index bbeffc7..b1fb785 100644 --- a/src/main/java/com/quseit/base/QBaseApp.java +++ b/src/main/java/com/quseit/base/QBaseApp.java @@ -1,19 +1,22 @@ package com.quseit.base; import android.app.Activity; +import android.content.Context; import android.os.Environment; import com.loopj.android.http.AsyncHttpClient; import com.quseit.config.BASE_CONF; +import com.quseit.util.FileUtils; import java.io.File; import java.util.ArrayList; public class QBaseApp { - private static final String TAG = "QBaseApp"; + private static final String TAG = "QBaseApp"; + + private AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); - private AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); public AsyncHttpClient getAsyncHttpClient() { return asyncHttpClient; } @@ -24,39 +27,44 @@ public class QBaseApp { } public static QBaseApp getInstance() { - if(null == instance) { - instance = new QBaseApp(); - } - return instance; + if (null == instance) { + instance = new QBaseApp(); + } + return instance; } // Activity 队列 ArrayList activities = new ArrayList<>(); - public void addActivity(Activity activity) { - this.activities.add(activity); + + public void addActivity(Activity activity) { + this.activities.add(activity); } + public void popActivity(Activity activity) { - this.activities.remove(activity); + this.activities.remove(activity); } // 本地目录 // TODO: 允许设置本地目录 private String root = null; - public String getOrCreateRoot(String subDir) { - String path = Environment.getExternalStorageDirectory().getAbsolutePath()+ (root==null?BASE_CONF.DEFAULT_ROOT:root) - +(subDir!=null - ? ("/"+subDir) + + public String getOrCreateRoot(Context context, String subDir) { +// String path = Environment.getExternalStorageDirectory().getAbsolutePath()+ (root==null?BASE_CONF.DEFAULT_ROOT:root) +// FileUtils.createTestDir(context,"test"); + String path = FileUtils.getQyPath(context) + (root == null ? BASE_CONF.DEFAULT_ROOT : root) + + (subDir != null + ? ("/" + subDir) : ""); - File root = new File(path); - if (!root.exists()) { - root.mkdirs(); + File root = new File(path); + if (!root.exists()) { + root.mkdirs(); } - return path; + return path; } // 资源回收 public void gc() { - System.gc(); - Runtime.getRuntime().gc(); + System.gc(); + Runtime.getRuntime().gc(); } } diff --git a/src/main/java/com/quseit/base/QBaseUpdateService.java b/src/main/java/com/quseit/base/QBaseUpdateService.java index 6cafb64..aae1478 100644 --- a/src/main/java/com/quseit/base/QBaseUpdateService.java +++ b/src/main/java/com/quseit/base/QBaseUpdateService.java @@ -30,109 +30,109 @@ import java.net.HttpURLConnection; import java.net.URL; public abstract class QBaseUpdateService extends Service { - private static int NOTIFICATION_ID = 0x20001;//通知栏消息id - - private static final String TAG = "QBaseUpdateService"; - private int NotifyIndex; - - private int titleId = 0; - private String UPDATELINK; - //private File updateDir = null; - private File updateFile = null; - - private final static int DOWNLOAD_COMPLETE = 0; - private final static int DOWNLOAD_FAIL = 1; - - private NotificationManager updateNotificationManager = null; - - private PendingIntent updatePendingIntent = null; - - private String type; - private String dst; - private String from; - private boolean replace = true; - - @TargetApi(5) - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - //获取传值 - //NotifyIndex = VeDate.getDatemsAsInt(); - NotifyIndex = NOTIFICATION_ID; - try { - titleId = intent.getIntExtra(BASE_CONF.EXTRA_CONTENT_URL1, 0); - } catch (Exception e) { - titleId = 0; - } - UPDATELINK = intent.getStringExtra(BASE_CONF.EXTRA_CONTENT_URL2); - type = intent.getStringExtra(BASE_CONF.EXTRA_CONTENT_URL3); - dst = intent.getStringExtra(BASE_CONF.EXTRA_CONTENT_URL4); - from = intent.getStringExtra(BASE_CONF.EXTRA_CONTENT_URL5); - String xx = intent.getStringExtra(BASE_CONF.EXTRA_CONTENT_URL6); - if (xx!=null && xx.equals("0")) { - replace = false; - } else { - replace = true; - } - - //创建文件 - if (NUtil.isExternalStorageExists()){ - try { - updateFile = new File(FileHelper.getBasePath(getDst(), "tmp"), getResources().getString(titleId)+"."+type); - } catch (NotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - this.updateNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); - - //设置下载过程中,点击通知栏,回到主界面 - Intent x = getSrvUpdateRet(); - if (x == null) { - Intent updateIntent = new Intent(); - updateIntent.setClassName(this.getPackageName(), this.getPackageName()+".MIndexAct"); - - updatePendingIntent = PendingIntent.getActivity(this,NOTIFICATION_ID,updateIntent,0); - } else { - Intent updateIntent = x; - updatePendingIntent = PendingIntent.getActivity(this,NOTIFICATION_ID,updateIntent,0); - } - - Notification updateNotification = NAction.getNotification(getApplicationContext(), getString(R.string.up_soft_update),"%0", updatePendingIntent, R.drawable.ic_download_nb, null,Notification.FLAG_ONGOING_EVENT); - - //发出通知 - updateNotificationManager.notify(NotifyIndex,updateNotification); - - //开启一个新的线程下载,如果使用Service同步下载,会导致ANR问题,Service本身也会阻塞 - new Thread(new updateRunnable()).start();//这个是下载的重点,是下载的过程 - } else { - Toast.makeText(getApplicationContext(), R.string.not_sd, Toast.LENGTH_SHORT).show(); - stopSelf(); - } - - return super.onStartCommand(intent, flags, startId); - } - - private Handler updateHandler = new Handler() { - @Override - public void handleMessage(Message msg) { - Intent intentS = new Intent(getApplicationContext(), getSelf()); - - switch(msg.what){ - case DOWNLOAD_COMPLETE: - updateNotificationManager.cancel(NotifyIndex); - - if (from!=null && !from.equals("")) { // NOTIFY - Log.d(TAG, "send notify to:"+from); - Intent intent1 = new Intent(from); - sendBroadcast(intent1); - } - - //点击安装PendingIntent - - //if (type.equals("apk")) { + private static int NOTIFICATION_ID = 0x20001;//通知栏消息id + + private static final String TAG = "QBaseUpdateService"; + private int NotifyIndex; + + private int titleId = 0; + private String UPDATELINK; + //private File updateDir = null; + private File updateFile = null; + + private final static int DOWNLOAD_COMPLETE = 0; + private final static int DOWNLOAD_FAIL = 1; + + private NotificationManager updateNotificationManager = null; + + private PendingIntent updatePendingIntent = null; + + private String type; + private String dst; + private String from; + private boolean replace = true; + + @TargetApi(5) + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + //获取传值 + //NotifyIndex = VeDate.getDatemsAsInt(); + NotifyIndex = NOTIFICATION_ID; + try { + titleId = intent.getIntExtra(BASE_CONF.EXTRA_CONTENT_URL1, 0); + } catch (Exception e) { + titleId = 0; + } + UPDATELINK = intent.getStringExtra(BASE_CONF.EXTRA_CONTENT_URL2); + type = intent.getStringExtra(BASE_CONF.EXTRA_CONTENT_URL3); + dst = intent.getStringExtra(BASE_CONF.EXTRA_CONTENT_URL4); + from = intent.getStringExtra(BASE_CONF.EXTRA_CONTENT_URL5); + String xx = intent.getStringExtra(BASE_CONF.EXTRA_CONTENT_URL6); + if (xx != null && xx.equals("0")) { + replace = false; + } else { + replace = true; + } + + //创建文件 + if (NUtil.isExternalStorageExists()) { + try { + updateFile = new File(FileHelper.getBasePath(getApplicationContext(), getDst(), "tmp"), getResources().getString(titleId) + "." + type); + } catch (NotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + this.updateNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + + //设置下载过程中,点击通知栏,回到主界面 + Intent x = getSrvUpdateRet(); + if (x == null) { + Intent updateIntent = new Intent(); + updateIntent.setClassName(this.getPackageName(), this.getPackageName() + ".MIndexAct"); + + updatePendingIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, updateIntent, 0); + } else { + Intent updateIntent = x; + updatePendingIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, updateIntent, 0); + } + + Notification updateNotification = NAction.getNotification(getApplicationContext(), getString(R.string.up_soft_update), "%0", updatePendingIntent, R.drawable.ic_download_nb, null, Notification.FLAG_ONGOING_EVENT); + + //发出通知 + updateNotificationManager.notify(NotifyIndex, updateNotification); + + //开启一个新的线程下载,如果使用Service同步下载,会导致ANR问题,Service本身也会阻塞 + new Thread(new updateRunnable()).start();//这个是下载的重点,是下载的过程 + } else { + Toast.makeText(getApplicationContext(), R.string.not_sd, Toast.LENGTH_SHORT).show(); + stopSelf(); + } + + return super.onStartCommand(intent, flags, startId); + } + + private Handler updateHandler = new Handler() { + @Override + public void handleMessage(Message msg) { + Intent intentS = new Intent(getApplicationContext(), getSelf()); + + switch (msg.what) { + case DOWNLOAD_COMPLETE: + updateNotificationManager.cancel(NotifyIndex); + + if (from != null && !from.equals("")) { // NOTIFY + Log.d(TAG, "send notify to:" + from); + Intent intent1 = new Intent(from); + sendBroadcast(intent1); + } + + //点击安装PendingIntent + + //if (type.equals("apk")) { /*Notification updateNotification = new Notification(); @@ -145,147 +145,150 @@ public abstract class QBaseUpdateService extends Service { //updateNotification.defaults = Notification.DEFAULT_VIBRATE; updateNotification.setLatestEventInfo(QBaseUpdateService.this, getString(R.string.app_name), getString(R.string.up_soft_done), updatePendingIntent); updateNotificationManager.notify(NotifyIndex, updateNotification);*/ - //} - //停止服务 - stopService(intentS); - break; - case DOWNLOAD_FAIL: + //} + //停止服务 + stopService(intentS); + break; + case DOWNLOAD_FAIL: - Notification updateNotification2 = NAction.getNotification(getApplicationContext(), getString(R.string.app_name),getString(R.string.up_update_failed), updatePendingIntent, R.drawable.ic_warning_nb, null, Notification.FLAG_AUTO_CANCEL); + Notification updateNotification2 = NAction.getNotification(getApplicationContext(), getString(R.string.app_name), getString(R.string.up_update_failed), updatePendingIntent, R.drawable.ic_warning_nb, null, Notification.FLAG_AUTO_CANCEL); - updateNotificationManager.notify(NotifyIndex, updateNotification2); - default: - stopService(intentS); + updateNotificationManager.notify(NotifyIndex, updateNotification2); + default: + stopService(intentS); - } - } - }; + } + } + }; - class updateRunnable implements Runnable { - Message message = updateHandler.obtainMessage(); - public void run() { - message.what = DOWNLOAD_COMPLETE; - try { - //增加权限; + class updateRunnable implements Runnable { + Message message = updateHandler.obtainMessage(); - if (!updateFile.exists()) { - updateFile.createNewFile(); - } - //下载函数,以QQ为例子 - //增加权限; - long downloadSize = downloadUpdateFile(UPDATELINK, updateFile); - //Log.d(TAG, "UPDATELINK:"+UPDATELINK+"-size:"+downloadSize+":type"+type+":dst"+dst); + public void run() { + message.what = DOWNLOAD_COMPLETE; + try { + //增加权限; - if (downloadSize>0){ + if (!updateFile.exists()) { + updateFile.createNewFile(); + } + //下载函数,以QQ为例子 + //增加权限; + long downloadSize = downloadUpdateFile(UPDATELINK, updateFile); + //Log.d(TAG, "UPDATELINK:"+UPDATELINK+"-size:"+downloadSize+":type"+type+":dst"+dst); - //下载成功 - if (type.equals("apk")) { - Log.d(TAG, "apk"); + if (downloadSize > 0) { - Uri uri = Uri.fromFile(updateFile); - Intent installIntent = new Intent(Intent.ACTION_VIEW); - installIntent.setDataAndType(uri, "application/vnd.android.package-archive"); - installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(installIntent); - } else { - String ext = FileHelper.getExt(updateFile.getAbsolutePath().toString(), ""); - String dext = FileHelper.getExt(dst, ""); - File destF = new File(dst); - Log.d(TAG, "ext:"+ext+"-dext:"+dext); - if (destF.exists()) { - if (destF.isFile()) { - destF.delete(); - } else if (destF.isDirectory()) { - Utils.deleteDir(destF); - } - } - - if (ext.equals(dext)) { // 后缀相同 - Log.d(TAG, "same ext"); - - updateFile.renameTo(destF); - - } else { - - if (ext.equals("zip")) { - Log.d(TAG, "zip found and unzip"); - InputStream content = new FileInputStream(updateFile); - Utils.unzip(content, dst, replace); - } - } - } - updateHandler.sendMessage(message); - } - } catch (Exception ex) { - ex.printStackTrace(); - message.what = DOWNLOAD_FAIL; - //下载失败 - updateHandler.sendMessage(message); - } - } - - public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception { - int downloadCount = 0; - int currentSize = 0; - long totalSize = 0; - int updateTotalSize = 0; - - HttpURLConnection httpConnection = null; - InputStream is = null; - FileOutputStream fos = null; - - try { - URL url = new URL(downloadUrl); - httpConnection = (HttpURLConnection)url.openConnection(); - httpConnection.setRequestProperty("User-Agent", "PacificHttpClient"); - if (currentSize > 0) { - httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-"); - } - httpConnection.setConnectTimeout(10000); - httpConnection.setReadTimeout(20000); - updateTotalSize = httpConnection.getContentLength(); - if (httpConnection.getResponseCode() == 404) { - throw new Exception("fail!"); - } - is = httpConnection.getInputStream(); - fos = new FileOutputStream(saveFile, false); - byte buffer[] = new byte[4096]; - int readsize = 0; - while ((readsize = is.read(buffer)) > 0) { - fos.write(buffer, 0, readsize); - totalSize += readsize; - //为了防止频繁的通知导致应用吃紧,百分比增加10才通知一次 - if ((downloadCount == 0)||(int) (totalSize*100/updateTotalSize)-10>downloadCount) { - downloadCount += 10; - - Notification updateNotification2 = NAction.getNotification(getApplicationContext(), getString(R.string.up_soft_downloading),(int)totalSize*100/updateTotalSize+"%", updatePendingIntent, R.drawable.ic_download_nb, null, Notification.FLAG_AUTO_CANCEL); - - updateNotificationManager.notify(NotifyIndex, updateNotification2); - } - } - } finally { - if (httpConnection != null) { - httpConnection.disconnect(); - } - if (is != null) { - is.close(); - } - if (fos != null) { - fos.close(); - } - } - return totalSize; - } - - } - - @Override - public IBinder onBind(Intent intent) { - return null; - } - - public abstract Intent getSrvUpdateRet(); - public abstract String getDst(); - public abstract Class getSelf(); + //下载成功 + if (type.equals("apk")) { + Log.d(TAG, "apk"); + + Uri uri = Uri.fromFile(updateFile); + Intent installIntent = new Intent(Intent.ACTION_VIEW); + installIntent.setDataAndType(uri, "application/vnd.android.package-archive"); + installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(installIntent); + } else { + String ext = FileHelper.getExt(updateFile.getAbsolutePath().toString(), ""); + String dext = FileHelper.getExt(dst, ""); + File destF = new File(dst); + Log.d(TAG, "ext:" + ext + "-dext:" + dext); + if (destF.exists()) { + if (destF.isFile()) { + destF.delete(); + } else if (destF.isDirectory()) { + Utils.deleteDir(destF); + } + } + + if (ext.equals(dext)) { // 后缀相同 + Log.d(TAG, "same ext"); + + updateFile.renameTo(destF); + + } else { + + if (ext.equals("zip")) { + Log.d(TAG, "zip found and unzip"); + InputStream content = new FileInputStream(updateFile); + Utils.unzip(content, dst, replace); + } + } + } + updateHandler.sendMessage(message); + } + } catch (Exception ex) { + ex.printStackTrace(); + message.what = DOWNLOAD_FAIL; + //下载失败 + updateHandler.sendMessage(message); + } + } + + public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception { + int downloadCount = 0; + int currentSize = 0; + long totalSize = 0; + int updateTotalSize = 0; + + HttpURLConnection httpConnection = null; + InputStream is = null; + FileOutputStream fos = null; + + try { + URL url = new URL(downloadUrl); + httpConnection = (HttpURLConnection) url.openConnection(); + httpConnection.setRequestProperty("User-Agent", "PacificHttpClient"); + if (currentSize > 0) { + httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-"); + } + httpConnection.setConnectTimeout(10000); + httpConnection.setReadTimeout(20000); + updateTotalSize = httpConnection.getContentLength(); + if (httpConnection.getResponseCode() == 404) { + throw new Exception("fail!"); + } + is = httpConnection.getInputStream(); + fos = new FileOutputStream(saveFile, false); + byte buffer[] = new byte[4096]; + int readsize = 0; + while ((readsize = is.read(buffer)) > 0) { + fos.write(buffer, 0, readsize); + totalSize += readsize; + //为了防止频繁的通知导致应用吃紧,百分比增加10才通知一次 + if ((downloadCount == 0) || (int) (totalSize * 100 / updateTotalSize) - 10 > downloadCount) { + downloadCount += 10; + + Notification updateNotification2 = NAction.getNotification(getApplicationContext(), getString(R.string.up_soft_downloading), (int) totalSize * 100 / updateTotalSize + "%", updatePendingIntent, R.drawable.ic_download_nb, null, Notification.FLAG_AUTO_CANCEL); + + updateNotificationManager.notify(NotifyIndex, updateNotification2); + } + } + } finally { + if (httpConnection != null) { + httpConnection.disconnect(); + } + if (is != null) { + is.close(); + } + if (fos != null) { + fos.close(); + } + } + return totalSize; + } + + } + + @Override + public IBinder onBind(Intent intent) { + return null; + } + + public abstract Intent getSrvUpdateRet(); + + public abstract String getDst(); + + public abstract Class getSelf(); } diff --git a/src/main/java/com/quseit/common/CrashHandler.java b/src/main/java/com/quseit/common/CrashHandler.java index a4627b2..1265830 100644 --- a/src/main/java/com/quseit/common/CrashHandler.java +++ b/src/main/java/com/quseit/common/CrashHandler.java @@ -10,6 +10,7 @@ import android.widget.Toast; import com.quseit.android.R; import com.quseit.common.db.AppLog; +import com.quseit.util.FileUtils; import com.quseit.util.NAction; import com.quseit.util.NUtil; @@ -55,7 +56,8 @@ public class CrashHandler implements UncaughtExceptionHandler { Log.d(TAG, "WriteSettings exits"); } - File log = new File(Environment.getExternalStorageDirectory()+"/"+NAction.getCode(context)+"_last_err.log"); +// File log = new File(Environment.getExternalStorageDirectory()+"/"+NAction.getCode(context)+"_last_err.log"); + File log = new File(FileUtils.getQyPath(context) +"/"+NAction.getCode(context)+"_last_err.log"); if (log.exists()) { log.delete(); } @@ -113,7 +115,8 @@ public class CrashHandler implements UncaughtExceptionHandler { public void run() { try { Looper.prepare(); - Toast.makeText(mContext, MessageFormat.format(mContext.getString(R.string.err_caught), Environment.getExternalStorageDirectory()+"/"+NAction.getCode(mContext)+"_last_err.log"), Toast.LENGTH_LONG).show(); +// Toast.makeText(mContext, MessageFormat.format(mContext.getString(R.string.err_caught), Environment.getExternalStorageDirectory()+"/"+NAction.getCode(mContext)+"_last_err.log"), Toast.LENGTH_LONG).show(); + Toast.makeText(mContext, MessageFormat.format(mContext.getString(R.string.err_caught), mContext.getApplicationContext().getExternalFilesDir(null).getAbsolutePath() +"/"+ NAction.getCode(mContext)+"_last_err.log"), Toast.LENGTH_LONG).show(); Looper.loop(); } catch (InflateException e) { Log.e(TAG, "error : ", e); diff --git a/src/main/java/com/quseit/service/DownloaderBase.java b/src/main/java/com/quseit/service/DownloaderBase.java index f517813..5c4660f 100644 --- a/src/main/java/com/quseit/service/DownloaderBase.java +++ b/src/main/java/com/quseit/service/DownloaderBase.java @@ -117,7 +117,7 @@ public abstract class DownloaderBase extends Service { + mArtist + "/"), mTitle + ext); } else { - dstFile = new File(QBaseApp.getInstance().getOrCreateRoot(mArtist) + "/" + mTitle + ext); + dstFile = new File(QBaseApp.getInstance().getOrCreateRoot(getApplicationContext(),mArtist) + "/" + mTitle + ext); } } downloadFile.renameTo(dstFile); @@ -274,15 +274,15 @@ public abstract class DownloaderBase extends Service { service_json = intent.getStringExtra(BASE_CONF.EXTRA_CONTENT_URL11); if (BASE_CONF.DEBUG) - Log.d(TAG, "onStartCommand[title:" + mTitle + ",artist:" + {Log.d(TAG, "onStartCommand[title:" + mTitle + ",artist:" + mArtist + ",album:" + mAlbum + ",completedSize:" - + mCompletedSize + "]"); + + mCompletedSize + "]");} // 创建文件 if (NUtil.isExternalStorageExists()) { try { - downloadFile = new File(QBaseApp.getInstance().getOrCreateRoot("tmp")+ "/"+ mArtist + "_" + mTitle + mExt); + downloadFile = new File(QBaseApp.getInstance().getOrCreateRoot(getApplicationContext(),"tmp")+ "/"+ mArtist + "_" + mTitle + mExt); } catch (NotFoundException e) { e.printStackTrace(); @@ -490,7 +490,7 @@ public abstract class DownloaderBase extends Service { if (NUtil.isExternalStorageExists()) { try { downloadFile = new File(QBaseApp - .getInstance().getOrCreateRoot("tmp")+ "/" + info.getPath()); + .getInstance().getOrCreateRoot(getApplicationContext(),"tmp")+ "/" + info.getPath()); } catch (NotFoundException e) { Log.d(TAG, "NotFoundException:" + e.getMessage()); e.printStackTrace(); @@ -573,6 +573,7 @@ public abstract class DownloaderBase extends Service { } } + @Override public void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); @@ -679,7 +680,7 @@ public abstract class DownloaderBase extends Service { long done = NStorage.getLongSP(getApplicationContext(), "download" + threadId); end = end - (sonThreadSize * (threadId - 1)); if ((done - (sonThreadSize * (threadId - 1)) >= end)) - runingTread--; + {runingTread--;} if (runingTread == 0) { for (int i = 1; i <= THREADCOUNT; i++) { diff --git a/src/main/java/com/quseit/util/FileHelper.java b/src/main/java/com/quseit/util/FileHelper.java index 0cef5b0..ab242d9 100644 --- a/src/main/java/com/quseit/util/FileHelper.java +++ b/src/main/java/com/quseit/util/FileHelper.java @@ -243,9 +243,11 @@ public class FileHelper { } } - public static File getBasePath(String parDir, String subdir) throws IOException { + public static File getBasePath(Context context, String parDir, String subdir) throws IOException { try { - File basePath = new File(Environment.getExternalStorageDirectory(), +// File basePath = new File(Environment.getExternalStorageDirectory(), +// FileUtils.createTestDir(context,"test"); + File basePath = new File(FileUtils.getQyPath(context), parDir); if (!basePath.exists()) { @@ -256,7 +258,9 @@ public class FileHelper { } File subPath = null; if (!subdir.equals("")) { - subPath = new File(Environment.getExternalStorageDirectory(), +// subPath = new File(Environment.getExternalStorageDirectory(), +// FileUtils.createTestDir(context,"test"); + subPath = new File(FileUtils.getQyPath(context), parDir + "/" + subdir); if (!subPath.exists()) { if (!subPath.mkdirs()) { @@ -270,10 +274,11 @@ public class FileHelper { throw new IOException(String.format("%s is not a directory!", basePath.toString())); } - if (subdir.equals("")) + if (subdir.equals("")) { return basePath; - else + } else { return subPath; + } } catch (Exception e) { e.printStackTrace(); return null; @@ -336,10 +341,11 @@ public class FileHelper { throw new IOException(String.format("%s is not a directory!", basePath.toString())); } - if (subdir.equals("")) + if (subdir.equals("")) { return basePath; - else + } else { return subPath; + } } public static String getFileName(String filename) { @@ -469,7 +475,7 @@ public class FileHelper { * @return */ public static File[] getFilesByType(File dir) { - if (dir==null) { + if (dir == null) { return null; } typeFiles = new ArrayList<>(); @@ -479,7 +485,7 @@ public class FileHelper { private static void addFile(File dir) { File[] dirFiles = dir.listFiles(); - if (dirFiles!=null) { + if (dirFiles != null) { for (File file : dirFiles) { if (file.isDirectory() && !file.getAbsolutePath().contains("/.")) { addFile(file); @@ -539,7 +545,6 @@ public class FileHelper { } - public static List filterExt(File dir, String[] exts, int size) { List filtered = new ArrayList<>(); List files = filterDir(dir); diff --git a/src/main/java/com/quseit/util/FileUtils.java b/src/main/java/com/quseit/util/FileUtils.java index 7807a2e..84cb1d7 100644 --- a/src/main/java/com/quseit/util/FileUtils.java +++ b/src/main/java/com/quseit/util/FileUtils.java @@ -48,8 +48,38 @@ import java.util.Set; public class FileUtils { private static final String TAG = "FileUtils"; - private FileUtils() { - // Utility class. + private FileUtils() {} + + public static String getScriptsRootPath(Context context){ + return getQyPath(context) + "/sl4a/scripts/"; + } + + public static String getCloudMapCachePath(Context context){ + return getAbsolutePath(context) + "/lib/.cloud_cache"; + } + + public static String getPyCachePath(Context context){ + return getAbsolutePath(context) + ".qpyc"; + } + + public static String getAbsoluteLogPath(Context context){ + return getAbsolutePath(context) + "/log/last.log"; + } + + public static String getLibDownloadTempPath(Context context){ + return getAbsolutePath(context) + "/cache"; + } + + public static String getAbsolutePath(Context context){ + return context.getExternalFilesDir(null).getPath() + "/qpython"; + } + + public static File getPath(Context context){ + return context.getExternalFilesDir(null); + } + + public static String getQyPath(Context context){ + return context.getExternalFilesDir(null).getAbsolutePath(); } static public boolean externalStorageMounted() { @@ -60,9 +90,14 @@ public class FileUtils { public static int chmod(File path, int mode) throws Exception { Class fileUtils = Class.forName("android.os.FileUtils"); - Method setPermissions = - fileUtils.getMethod("setPermissions", String.class, int.class, int.class, int.class); - return (Integer) setPermissions.invoke(null, path.getAbsolutePath(), mode, -1, -1); + Method setPermissions = fileUtils.getMethod("setPermissions", String.class, int.class, int.class, int.class); + Object invokePer = setPermissions.invoke(null, path.getAbsolutePath(), mode, -1, -1); + if (invokePer instanceof Integer){ + return (Integer) invokePer; + }else { + return 0; + } +// return (Integer) setPermissions.invoke(null, path.getAbsolutePath(), mode, -1, -1); } @RequiresApi(api = Build.VERSION_CODES.O) @@ -74,7 +109,7 @@ public class FileUtils { perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); - perms.add(PosixFilePermission.OWNER_EXECUTE); + perms.add(PosixFilePermission.OTHERS_EXECUTE); perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); @@ -85,11 +120,14 @@ public class FileUtils { public static boolean recursiveChmod(File root, int mode) throws Exception { boolean success = chmod(root, mode) == 0; - for (File path : root.listFiles()) { - if (path.isDirectory()) { - success = recursiveChmod(path, mode); + File[] files = root.listFiles(); + if (files != null){ + for (File path : files) { + if (path.isDirectory()) { + success = recursiveChmod(path, mode); + } + success &= (chmod(path, mode) == 0); } - success &= (chmod(path, mode) == 0); } return success; } @@ -98,10 +136,14 @@ public class FileUtils { boolean result = true; if (path.exists()) { if (path.isDirectory()) { - for (File child : path.listFiles()) { - result &= delete(child); + File[] files = path.listFiles(); + if (files != null){ + for (File child : files) { + result &= delete(child); + } } - result &= path.delete(); // Delete empty directory. + // Delete empty directory. + result &= path.delete(); } if (path.isFile()) { result &= path.delete(); @@ -156,16 +198,17 @@ public class FileUtils { return true; } - public static File getExternalDownload() { - try { - Class c = Class.forName("android.os.Environment"); - Method m = c.getDeclaredMethod("getExternalStoragePublicDirectory", String.class); - String download = c.getDeclaredField("DIRECTORY_DOWNLOADS").get(null).toString(); - return (File) m.invoke(null, download); - } catch (Exception e) { - return new File(Environment.getExternalStorageDirectory(), "Download"); - } - } +// public static File getExternalDownload() { +// try { +// Class c = Class.forName("android.os.Environment"); +// Method m = c.getDeclaredMethod("getExternalStoragePublicDirectory", String.class); +// String download = c.getDeclaredField("DIRECTORY_DOWNLOADS").get(null).toString(); +// return (File) m.invoke(null, download); +// } catch (Exception e) { +//// return new File(Environment.getExternalStorageDirectory(), "Download"); +// return new File(Environment.getExternalStorageDirectory(), "Download"); +// } +// } public static boolean rename(File file, String name) { return file.renameTo(new File(file.getParent(), name)); diff --git a/src/main/java/com/quseit/util/Utils.java b/src/main/java/com/quseit/util/Utils.java index dd6bc7a..2f5e8d3 100644 --- a/src/main/java/com/quseit/util/Utils.java +++ b/src/main/java/com/quseit/util/Utils.java @@ -188,15 +188,17 @@ public class Utils { } } - public static void createDirectoryOnExternalStorage(String path) { + public static void createDirectoryOnExternalStorage(Context context,String path) { try { if(Environment.getExternalStorageState().equalsIgnoreCase("mounted")) { - File file = new File(Environment.getExternalStorageDirectory(), path); +// File file = new File(Environment.getExternalStorageDirectory(), path); + File file = new File(FileUtils.getQyPath(context), path); if (!file.exists()) { try { file.mkdirs(); - Log.d(TAG, "createDirectoryOnExternalStorage created " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +path); +// Log.d(TAG, "createDirectoryOnExternalStorage created " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +path); + Log.d(TAG, "createDirectoryOnExternalStorage created " + FileUtils.getQyPath(context) + "/" +path); } catch (Exception e) { Log.e(TAG,"createDirectoryOnExternalStorage error: ", e); } @@ -248,7 +250,8 @@ public class Utils { // 如SD卡已存在,则存储;反之存在data目录下 if (hasSdcard()) { // SD卡路径 - filePath = Environment.getExternalStorageDirectory() +// filePath = Environment.getExternalStorageDirectory() + filePath = FileUtils.getQyPath(context) + File.separator + dirName; } else { filePath = context.getCacheDir().getPath() + File.separator -- Gitee From 7bf954a9315dd57fec4fb7d4c8e314593e062c20 Mon Sep 17 00:00:00 2001 From: jianxiang Date: Wed, 12 Jan 2022 17:26:33 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix:=E4=BF=AE=E5=A4=8D=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/quseit/util/FileUtils.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/quseit/util/FileUtils.java b/src/main/java/com/quseit/util/FileUtils.java index 84cb1d7..b7aba80 100644 --- a/src/main/java/com/quseit/util/FileUtils.java +++ b/src/main/java/com/quseit/util/FileUtils.java @@ -71,7 +71,8 @@ public class FileUtils { } public static String getAbsolutePath(Context context){ - return context.getExternalFilesDir(null).getPath() + "/qpython"; +// return context.getExternalFilesDir(null).getPath() + "/qpython"; + return Environment.getExternalStorageDirectory().getPath() + "/qpython"; } public static File getPath(Context context){ @@ -79,7 +80,8 @@ public class FileUtils { } public static String getQyPath(Context context){ - return context.getExternalFilesDir(null).getAbsolutePath(); +// return context.getExternalFilesDir(null).getAbsolutePath(); + return Environment.getExternalStorageDirectory().getPath(); } static public boolean externalStorageMounted() { -- Gitee