fei.wang
7 天以前 ae7b22322555448d95fd56f505bafa325c167a26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
<template>
  <view class="container">
    <button @click="saveLog" class="save-button">保存日志文件</button>
  </view>
</template>
 
<script>
// 导入必要的 Android 类
const android = plus.android;
const Intent = android.importClass('android.content.Intent');
const Settings = android.importClass('android.provider.Settings');
const Uri = android.importClass('android.net.Uri');
const Build = android.importClass('android.os.Build');
const Environment = android.importClass('android.os.Environment');
const MediaStore = android.importClass('android.provider.MediaStore');
const ContentValues = android.importClass('android.content.ContentValues');
const ContentResolver = android.importClass('android.content.ContentResolver');
 
export default {
  methods: {
    async saveLog() {
      try {
        // 直接尝试写入文件,避免依赖权限检查
        const logContent = `[${new Date().toLocaleString()}] 设备日志记录...\n`;
        const fileName = `vehicle_log_${new Date().getTime()}.txt`;
        
        // 使用两种方法尝试保存
        let result = await this.tryWriteWithMediaStore(fileName, logContent);
        if (!result) {
          result = await this.tryWriteWithLegacyMethod(fileName, logContent);
        }
        
        if (result) {
          uni.showToast({
            title: '日志保存成功',
            icon: 'success',
            duration: 3000
          });
          console.log(`文件已保存至: ${result}`);
        } else {
          throw new Error('所有保存方法均失败');
        }
      } catch (err) {
        console.error('保存失败:', err);
        uni.showToast({
          title: `保存失败: ${err.message || err}`,
          icon: 'none',
          duration: 5000
        });
        
        // 保存失败时显示详细错误信息
        this.showErrorDetails(err);
      }
    },
 
    // 方法1: 使用 MediaStore API (Android 10+推荐)
    async tryWriteWithMediaStore(fileName, content) {
      return new Promise((resolve) => {
        try {
          // 获取ContentResolver
          const mainActivity = plus.android.runtimeMainActivity();
          const resolver = mainActivity.getContentResolver();
          
          // 设置文件信息
          const contentValues = new ContentValues();
          contentValues.put(MediaStore.Downloads.DISPLAY_NAME, fileName);
          contentValues.put(MediaStore.Downloads.MIME_TYPE, "text/plain");
          
          // 对于Android 10+需要指定RELATIVE_PATH
          if (Build.VERSION.SDK_INT >= 29) {
            contentValues.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
          }
          
          // 创建文件URI
          const collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
          const fileUri = resolver.insert(collection, contentValues);
          
          if (!fileUri) {
            console.error("无法创建文件URI");
            resolve(false);
            return;
          }
          
          // 写入文件内容
          const outputStream = resolver.openOutputStream(fileUri);
          outputStream.write(plus.android.invoke(content, "getBytes", "UTF-8"));
          outputStream.close();
          
          console.log("通过MediaStore写入成功:", fileUri.toString());
          resolve(fileUri.toString());
        } catch (e) {
          console.warn("MediaStore写入失败:", e);
          resolve(false);
        }
      });
    },
 
    // 方法2: 传统文件系统方法 (兼容旧版Android)
    async tryWriteWithLegacyMethod(fileName, content) {
      return new Promise((resolve) => {
        try {
          // 获取下载目录路径
          const downloadsDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS
          ).toString();
          
          const filePath = `${downloadsDir}/${fileName}`;
          
          // 使用Java文件API写入
          const File = plus.android.importClass('java.io.File');
          const FileOutputStream = plus.android.importClass('java.io.FileOutputStream');
          
          const file = new File(filePath);
          const fos = new FileOutputStream(file);
          fos.write(plus.android.invoke(content, "getBytes", "UTF-8"));
          fos.close();
          
          console.log("传统方法写入成功:", filePath);
          resolve(filePath);
        } catch (e) {
          console.warn("传统方法写入失败:", e);
          resolve(false);
        }
      });
    },
 
    // 显示错误详情
    showErrorDetails(error) {
      let message = "未知错误";
      
      if (error && error.message) {
        message = error.message;
      }
      
      // 检查存储状态
      const storageState = Environment.getExternalStorageState();
      const isMounted = Environment.MEDIA_MOUNTED.equals(storageState);
      
      // 获取Android版本信息
      const sdkInt = Build.VERSION.SDK_INT;
      const versionName = Build.VERSION.RELEASE;
      
      uni.showModal({
        title: '错误详情',
        content: `错误信息: ${message}
Android版本: ${sdkInt} (${versionName})
存储状态: ${storageState} (${isMounted ? '已挂载' : '未挂载'})
应用ID: ${plus.runtime.appid}`,
        showCancel: false,
        confirmText: '确定'
      });
    },
 
    // 打开存储设置
    openStorageSettings() {
      try {
        const intent = new Intent(Settings.ACTION_INTERNAL_STORAGE_SETTINGS);
        plus.android.runtimeMainActivity().startActivity(intent);
      } catch (e) {
        console.error("打开存储设置失败:", e);
      }
    }
  }
}
</script>
 
<style>
.container {
  padding: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}
 
.save-button {
  width: 300px;
  height: 60px;
  background-color: #2196F3;
  color: white;
  border-radius: 12px;
  font-size: 20px;
  font-weight: bold;
  box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}
</style>