我试图通过这样的计时器在我的服务中调用我的方法 -
public void run() {
walkdir(dir);// call method
}
但它永远不会被调用或显示任何Toast消息。我错过了什么吗?我坚持了一个多小时。这是我的完整代码 -
public class FreezeService extends Service {
Context context = this;
// constant
public static final long NOTIFY_INTERVAL = 5 * 1000; // 10 seconds
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
@Override
public IBinder onBind(Intent intent) {
return null;
}
// getting SDcard root path
File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath());
@Override
public void onCreate() {
// cancel if already existed
if (mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0,
NOTIFY_INTERVAL);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;// this make the service sticky which prevents it
// from getting killed by advanced task killers
}
class TimeDisplayTimerTask extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run() {
walkdir(dir);// call method
}
});
}
}
public void walkdir(File dir) {
String Patternjpg = "x23213jdfkjsdbfnsfddns";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
if (listFile[i].getName().contains(Patternjpg)) {
Toast.makeText(getBaseContext(), "method got called",
Toast.LENGTH_SHORT).show();
// Do what ever u want
listFile[i].delete();
}
}
}
}
}
答案 0 :(得分:0)
答案是:
鉴于此文件夹结构:
稍微修改你的代码以获得更好的输出并允许在我的本地计算机上进行测试(现在无法在android中测试):
public class WalkDir {
public static void main(String[] args) {
walkdir(new File("C:\\test"));
}
public static void walkdir(File dir) {
String Patternjpg = "x23213jdfkjsdbfnsfddns";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
System.out.println("directory found" + listFile[i].getPath());
walkdir(listFile[i]);
} else {
if (listFile[i].getName().contains(Patternjpg)) {
System.out.println("method got called, deleting " + listFile[i].getPath());
// Do what ever u want
listFile[i].delete();
}
}
}
}
}
}
我有正确的输出:
directory found C:\test\1
directory found C:\test\2
directory found C:\test\3
directory found C:\test\3\1
method got called, deleting C:\test\3\x23213jdfkjsdbfnsfddns.js
Java中的变量和方法名称是lowerCamelCase。所以:
String patternJPG = "x23213jdfkjsdbfnsfddns";
public static void walkDir(File dir) {
另外,我会在patternJPG
递归方法之外提取walkDir
变量:
private final String patternJPG = "x23213jdfkjsdbfnsfddns";
public void walkDir(File dir) {
// method as is...
}