MCPcopy Create free account
hub / github.com/Acode-Foundation/Acode / enableStaticContext

Function enableStaticContext

hooks/post-process.js:151–211  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

149}
150
151function enableStaticContext() {
152 try {
153 const prefix = execSync('npm prefix').toString().trim();
154 const packageName = getPackageName();
155 const mainActivityPath = path.join(
156 prefix,
157 'platforms/android/app/src/main/java',
158 packageName.replace(/\./g, '/'),
159 'MainActivity.java'
160 );
161
162 if (!fs.existsSync(mainActivityPath)) {
163 console.warn('[Cordova Hook] ⚠️ MainActivity.java not found at', mainActivityPath);
164 return;
165 }
166
167 let content = fs.readFileSync(mainActivityPath, 'utf-8');
168
169 // Skip if fully patched
170 if (
171 content.includes('WeakReference<Context>') &&
172 content.includes('public static Context getContext()') &&
173 content.includes('weakContext = new WeakReference<>(this);')
174 ) {
175 console.log('[Cordova Hook] ✅ Static context already enabled, skipping');
176 return;
177 }
178
179 // Add missing imports
180 if (!content.includes('import java.lang.ref.WeakReference;')) {
181 content = content.replace(
182 /import org\.apache\.cordova\.\*;/,
183 match =>
184 match +
185 '\nimport android.content.Context;\nimport java.lang.ref.WeakReference;'
186 );
187 }
188
189 // Inject static field and method into class body
190 content = content.replace(
191 /public class MainActivity extends CordovaActivity\s*\{/,
192 match =>
193 match +
194 `\n\n private static WeakReference<Context> weakContext;\n\n` +
195 ` public static Context getContext() {\n` +
196 ` return weakContext != null ? weakContext.get() : null;\n` +
197 ` }\n`
198 );
199
200 // Insert weakContext assignment inside onCreate
201 content = content.replace(
202 /super\.onCreate\(savedInstanceState\);/,
203 `super.onCreate(savedInstanceState);\n weakContext = new WeakReference<>(this);`
204 );
205
206 fs.writeFileSync(mainActivityPath, content, 'utf-8');
207 console.log('[Cordova Hook] ✅ Enabled static context');
208 } catch (err) {

Callers 1

post-process.jsFile · 0.85

Calls 4

getPackageNameFunction · 0.85
logMethod · 0.80
toStringMethod · 0.45
errorMethod · 0.45

Tested by

no test coverage detected