Proyectos de Subversion LeadersLinked - Android

Rev

Rev 3 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
3 efrain 1
package com.cesams.leaderslinked.v2;
2
 
3
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
4
 
5
import android.Manifest;
6
 
7
import androidx.activity.result.ActivityResultLauncher;
8
import androidx.activity.result.contract.ActivityResultContracts;
9
import androidx.annotation.NonNull;
10
import androidx.annotation.Nullable;
11
import androidx.annotation.RequiresApi;
12
import androidx.appcompat.app.AppCompatActivity;
13
import androidx.core.app.ActivityCompat;
14
import androidx.core.content.ContextCompat;
15
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
16
import androidx.core.view.ViewCompat;
17
import androidx.core.view.WindowInsetsCompat;
18
 
19
 
20
import android.content.pm.PackageManager;
21
import android.annotation.SuppressLint;
22
import android.content.Intent;
23
import android.content.res.Configuration;
24
import android.net.Uri;
25
import android.os.Build;
26
import android.os.Bundle;
27
import android.os.Environment;
28
import android.provider.MediaStore;
29
import android.util.Log;
30
import android.view.KeyEvent;
31
import android.view.View;
32
import android.webkit.JavascriptInterface;
33
import android.webkit.ValueCallback;
34
import android.webkit.WebChromeClient;
35
import android.webkit.WebSettings;
36
import android.webkit.WebView;
37
import android.webkit.WebViewClient;
38
 
39
import java.io.File;
40
import java.io.IOException;
41
import java.text.SimpleDateFormat;
42
import java.util.ArrayList;
43
import java.util.Date;
44
 
45
public class MainActivity extends AppCompatActivity {
46
 
47
    private TouchyWebView mWebView = null;
48
 
49
 
50
    private SwipeRefreshLayout mSwipeRefreshLayout;
51
 
52
    private static String file_type = "*/*";
53
    private String cam_file_data = null;
54
    private ValueCallback<Uri> file_data;
55
    private ValueCallback<Uri[]> file_path;
56
    private final static int file_req_code = 1;
57
 
4 efrain 58
    private final static String _URL = "https://stanging.leaderslinked.com";
3 efrain 59
 
60
    private ActivityResultLauncher<Intent> fileChooserLauncher;
61
 
62
 
63
    @RequiresApi(api = Build.VERSION_CODES.M)
64
    @Override
65
    protected void onCreate(Bundle savedInstanceState) {
66
        super.onCreate(savedInstanceState);
67
        setContentView(R.layout.activity_main);
68
 
69
 
70
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.swipeRefreshLayout), (v, insets) -> {
71
            int top = insets.getInsets(WindowInsetsCompat.Type.systemBars()).top;
72
            int bottom = insets.getInsets(WindowInsetsCompat.Type.systemBars()).bottom;
73
            int left = insets.getInsets(WindowInsetsCompat.Type.systemBars()).left;
74
            int right = insets.getInsets(WindowInsetsCompat.Type.systemBars()).right;
75
 
76
            v.setPadding(left, top, right, bottom);
77
 
78
            return insets;
79
        });
80
 
81
 
82
        fileChooserLauncher = registerForActivityResult(
83
                new ActivityResultContracts.StartActivityForResult(),
84
                result -> {
85
                    // For Android 5.0 (Lollipop) and above
86
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
87
                        if (file_path == null) {
88
                            return;
89
                        }
90
                        Uri[] uris = WebChromeClient.FileChooserParams.parseResult(result.getResultCode(), result.getData());
91
                        if (uris == null) {
92
                            if (cam_file_data != null) {
93
                                uris = new Uri[]{Uri.parse(cam_file_data)};
94
                            }
95
                        }
96
                        file_path.onReceiveValue(uris);
97
                        file_path = null;
98
                    } else { // For older versions
99
                        if (file_data == null) {
100
                            return;
101
                        }
102
                        Uri resultUri = (result.getData() == null || result.getResultCode() != RESULT_OK) ? null : result.getData().getData();
103
                        file_data.onReceiveValue(resultUri);
104
                        file_data = null;
105
                    }
106
                    cam_file_data = null;
107
                });
108
 
109
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
110
 
111
        mSwipeRefreshLayout.setOnChildScrollUpCallback(new SwipeRefreshLayout.OnChildScrollUpCallback() {
112
            @Override
113
            public boolean canChildScrollUp(@NonNull SwipeRefreshLayout parent, @Nullable View child) {
114
                return mWebView.canScrollVertically(-1);
115
            }
116
        });
117
 
118
 
119
 
120
 
121
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
122
            @Override
123
            public void onRefresh() {
124
                mWebView.reload();
125
            }
126
        });
127
 
128
 
129
 
130
 
131
        mWebView = (TouchyWebView) findViewById(R.id.webView);
132
        // mWebView.setiTouckWebView(this); // No longer needed
133
 
134
        /*
135
        mWebView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
136
            @Override
137
            public void onScrollChange(View v,
138
                                       int scrollX,
139
                                       int scrollY,
140
                                       int oldScrollX,
141
                                       int oldScrollY) {
142
                System.out.println(" View.OnScrollChangeListener scrollY = " + scrollY +  "oldScrollX = " + oldScrollX);
143
            }
144
        });
145
        */
146
       // mWebView.setWebViewClient( mCesaWebViewClient);
147
 
148
        mWebView.addJavascriptInterface(new JavaScriptShareInterface(), "AndroidShareHandler");
149
 
150
 
151
 
152
 
153
        WebSettings webSettings = mWebView.getSettings();
154
        webSettings.setJavaScriptEnabled(true);
155
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
156
        webSettings.setAllowFileAccess(true);
157
        webSettings.setAllowContentAccess(true);
158
        webSettings.setAllowFileAccessFromFileURLs(true);
159
        webSettings.setAllowUniversalAccessFromFileURLs(true);
160
        webSettings.setDomStorageEnabled(true);
161
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
162
        webSettings.setDisplayZoomControls(true);
163
        webSettings.setBuiltInZoomControls(true);
164
 
165
        webSettings.setMediaPlaybackRequiresUserGesture(false);
166
 
167
 
168
        mWebView.setWebViewClient(new WebViewClient() {
169
 
170
 
171
 
172
 
173
            @Override
174
            public void onPageFinished(WebView view, String url) {
175
                findViewById(R.id.webView).setVisibility(View.VISIBLE);
176
                mSwipeRefreshLayout.setRefreshing(false);
177
 
178
 
179
            }
180
 
181
 
182
            @Override
183
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
184
                if(url.contains("leaderslinked.com") ) return false;
185
 
186
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
187
                MainActivity.this.startActivity(intent);
188
                return true;
189
            }
190
 
191
        });
192
 
193
        mWebView.setWebChromeClient(new WebChromeClient()
194
        {
195
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
196
 
197
                if(file_permission() && Build.VERSION.SDK_INT >= 21) {
198
                    file_path = filePathCallback;
199
                    Intent takePictureIntent = null;
200
                    Intent takeVideoIntent = null;
201
 
202
                    boolean includeVideo = false;
203
                    boolean includePhoto = false;
204
 
205
                    paramCheck:
206
                    for (String acceptTypes : fileChooserParams.getAcceptTypes()) {
207
                        String[] splitTypes = acceptTypes.split(", ?+");
208
                        for (String acceptType : splitTypes) {
209
                            switch (acceptType) {
210
                                case "*/*":
211
                                    includePhoto = true;
212
                                    includeVideo = true;
213
                                    break paramCheck;
214
                                case "image/*":
215
                                    includePhoto = true;
216
                                    break;
217
                                case "video/*":
218
                                    includeVideo = true;
219
                                    break;
220
                            }
221
                        }
222
                    }
223
 
224
                    if (fileChooserParams.getAcceptTypes().length == 0) {
225
                        includePhoto = true;
226
                        includeVideo = true;
227
                    }
228
 
229
                    if (includePhoto) {
230
                        takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
231
                        if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
232
                            File photoFile = null;
233
                            try {
234
                                photoFile = create_image();
235
                                takePictureIntent.putExtra("PhotoPath", cam_file_data);
236
                            } catch (IOException ex) {
237
                                Log.e("MainClass" , "Image file creation failed", ex);
238
                            }
239
                            if (photoFile != null) {
240
                                cam_file_data = "file:" + photoFile.getAbsolutePath();
241
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
242
                            } else {
243
                                cam_file_data = null;
244
                                takePictureIntent = null;
245
                            }
246
                        }
247
                    }
248
 
249
                    if (includeVideo) {
250
                        takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
251
                        if (takeVideoIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
252
                            File videoFile = null;
253
                            try {
254
                                videoFile = create_video();
255
                            } catch (IOException ex) {
256
                                Log.e("MainClass" , "Video file creation failed", ex);
257
                            }
258
                            if (videoFile != null) {
259
                                cam_file_data = "file:" + videoFile.getAbsolutePath();
260
                                takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(videoFile));
261
                            } else {
262
                                cam_file_data = null;
263
                                takeVideoIntent = null;
264
                            }
265
                        }
266
                    }
267
 
268
                    Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
269
                    contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
270
                    contentSelectionIntent.setType(file_type);
271
 
272
 
273
                    Intent[] intentArray;
274
                    if (takePictureIntent != null && takeVideoIntent != null) {
275
                        intentArray = new Intent[]{takePictureIntent, takeVideoIntent};
276
                    } else if (takePictureIntent != null) {
277
                        intentArray = new Intent[]{takePictureIntent};
278
                    } else if (takeVideoIntent != null) {
279
                        intentArray = new Intent[]{takeVideoIntent};
280
                    } else {
281
                        intentArray = new Intent[0];
282
                    }
283
 
284
                    Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
285
                    chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
286
                    chooserIntent.putExtra(Intent.EXTRA_TITLE, "File chooser");
287
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
288
                    fileChooserLauncher.launch(chooserIntent);
289
                    return true;
290
                } else {
291
                    return false;
292
                }
293
            }
294
        });
295
 
296
        mWebView.loadUrl(_URL);
297
    }
298
 
299
 
300
 
301
    /* // No longer needed
302
    public void reloadPage() {
303
        System.out.println("reloadPage");
304
 
305
        if(!mSwipeRefreshLayout.isRefreshing()) {
306
 
307
            mSwipeRefreshLayout.setRefreshing(true);
308
            mWebView.reload();
309
 
310
        }
311
    }
312
    */
313
 
314
 
315
 
316
    @Override
317
    public boolean onKeyDown(int keyCode, KeyEvent event) {
318
        if ((keyCode == KeyEvent.KEYCODE_BACK) && this.mWebView.canGoBack()) {
319
            this.mWebView.goBack();
320
            return true;
321
        }
322
 
323
        return super.onKeyDown(keyCode, event);
324
    }
325
 
326
 
327
 
328
 
329
    @Override
330
    protected void onSaveInstanceState(Bundle outState){
331
        super.onSaveInstanceState(outState);
332
 
333
        // Save the state of the WebView
334
        mWebView.saveState(outState);
335
    }
336
 
337
    @Override
338
    protected void onRestoreInstanceState(Bundle savedInstanceState){
339
        super.onRestoreInstanceState(savedInstanceState);
340
 
341
        // Restore the state of the WebView
342
        mWebView.restoreState(savedInstanceState);
343
    }
344
 
345
    @Override
346
    public void onConfigurationChanged(Configuration newConfig){
347
        super.onConfigurationChanged(newConfig);
348
    }
349
 
350
    public boolean file_permission(){
351
        /*
352
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (checkSelfPermission(WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED || checkSelfPermission(CAMERA) == PackageManager.PERMISSION_DENIED)) {
353
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{WRITE_EXTERNAL_STORAGE, CAMERA}, 1);
354
            return true;
355
        }else{
356
            return false;
357
        }*/
358
 
359
        int checkPermissionExternal = PackageManager.PERMISSION_GRANTED;
360
        int checkPermissionReadMediaAudio = PackageManager.PERMISSION_GRANTED;
361
        int checkPermissionReadMediaVideo = PackageManager.PERMISSION_GRANTED;
362
        int checkPermissionReadMediaImages = PackageManager.PERMISSION_GRANTED;
363
 
364
        int checkPermissionCamera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
365
 
366
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
367
            checkPermissionExternal = ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE);
368
        } else {
369
            checkPermissionReadMediaAudio = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO);
370
            checkPermissionReadMediaVideo = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_VIDEO);
371
            checkPermissionReadMediaImages = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES);
372
        }
373
 
374
 
375
        boolean ok = checkPermissionCamera == PackageManager.PERMISSION_GRANTED;
376
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
377
            ok = ok && checkPermissionExternal == PackageManager.PERMISSION_GRANTED;
378
        } else {
379
            ok = ok && checkPermissionReadMediaAudio == PackageManager.PERMISSION_GRANTED;
380
            ok = ok && checkPermissionReadMediaVideo == PackageManager.PERMISSION_GRANTED;
381
            ok = ok && checkPermissionReadMediaImages == PackageManager.PERMISSION_GRANTED;
382
        }
383
 
384
        if(!ok) {
385
 
386
            ArrayList<String> newPermissionList = new ArrayList<>();
387
 
388
            if(checkPermissionCamera != PackageManager.PERMISSION_GRANTED) {
389
                newPermissionList.add(Manifest.permission.CAMERA);
390
            }
391
 
392
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
393
                if(checkPermissionExternal != PackageManager.PERMISSION_GRANTED) {
394
                    newPermissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
395
                }
396
            } else {
397
                if(checkPermissionReadMediaAudio != PackageManager.PERMISSION_GRANTED) {
398
                    newPermissionList.add(Manifest.permission.READ_MEDIA_AUDIO);
399
                }
400
                if(checkPermissionReadMediaVideo != PackageManager.PERMISSION_GRANTED) {
401
                    newPermissionList.add(Manifest.permission.READ_MEDIA_VIDEO);
402
                }
403
                if(checkPermissionReadMediaImages != PackageManager.PERMISSION_GRANTED) {
404
                    newPermissionList.add(Manifest.permission.READ_MEDIA_IMAGES);
405
                }
406
            }
407
 
408
 
409
 
410
 
411
            String permissions[] = newPermissionList.toArray(new String[newPermissionList.size()]);
412
            ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
413
            return true;
414
        } else {
415
            return false;
416
        }
417
    }
418
 
419
    private File create_image() throws IOException {
420
        @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
421
        String imageFileName = "img_"+timeStamp+"_";
422
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
423
        return File.createTempFile(imageFileName,".jpg",storageDir);
424
    }
425
 
426
    private File create_video() throws IOException {
427
        @SuppressLint("SimpleDateFormat")
428
        String file_name = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
429
        String new_name = "file_"+file_name+"_";
430
        File sd_directory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
431
        return File.createTempFile(new_name, ".3gp", sd_directory);
432
    }
433
 
434
 
435
    private class JavaScriptShareInterface {
436
 
437
 
438
        @JavascriptInterface
439
        public void share(String url, String title, String content) {
440
            try {
441
                Intent shareIntent = new Intent(Intent.ACTION_SEND);
442
                shareIntent.setType("text/plain");
443
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, title);
444
                String shareMessage= "\n" +  content + "\n\n";
445
                shareMessage = shareMessage + url +"\n\n";
446
                shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage);
447
 
448
                Intent chooserIntent = Intent.createChooser(shareIntent, "choose one");
449
 
450
                startActivity(chooserIntent);
451
            } catch(Exception e) {
452
                //e.toString();
453
            }
454
        }
455
 
456
    }
457
}