我正在创建一个AIDL接口,其中有一个方法需要创建一个临时文件。在从MyService.Stub
类派生的类中实现此方法时,我有以下代码:
class ServiceImplementation extends DmServiceInterface.Stub {
// ...
@Override
public void uploadResource(ParcelFileDescriptor pipe) {
//...
File tmpDir = context.getCacheDir();
Log.d(TAG, String.format("Temp dir: %s", tmpDir));
File uploadFile = File.createTempFile("dm_", ".bin", tmpDir);
Log.i(TAG, String.format("Setting up upload file at %s", uploadFile.getAbsolutePath()));
//...
}
//...
}
其中context
引用保存在相应服务实例的onCreate()回调中:
public class CcService extends Service {
private Context context;
// ...
public void onCreate() {
context = getApplicationContext();
//...
}
}
当我在模拟器下运行代码时,我得到以下内容:
D/dm.service: temp dir: null
W/ContextImpl: Unable to create files subdir /data/user/0/com.dm.ccserver/cache
E/dm.service: open failed: ENOENT (No such file or directory)
W/System.err: java.io.IOException: open failed: ENOENT (No such file or directory)
W/System.err: at java.io.File.createNewFile(File.java:939)
W/System.err: at java.io.File.createTempFile(File.java:1004)
W/System.err: at com.dm.ccserver.ServiceImplementation.uploadResource(ServiceImplementation.java:69)
W/System.err: at com.dm.ccserver.DmServiceInterface$Stub.onTransact(DmServiceInterface.java:73)
W/System.err: at android.os.Binder.execTransact(Binder.java:453)
getCacheDir()
会返回null
?缓存目录确实存在:
root@generic_x86:/ # ls -ld /data/user/0/com.dm.ccserver/cache
drwxrwx--x u0_a66 u0_a66 2016-11-22 17:14 cache