Java tutorial
/** * Copyright 2015 Google Inc. All Rights Reserved. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.company.millenium.iwannask; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.net.http.SslError; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.webkit.CookieSyncManager; import android.webkit.GeolocationPermissions; import android.webkit.JavascriptInterface; import android.webkit.PermissionRequest; import android.webkit.SslErrorHandler; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener { private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; private static final String TAG = "MainActivity"; private String URL; private BroadcastReceiver mRegistrationBroadcastReceiver; WebView myWebView; boolean loadingFinished = true; boolean redirect = false; private ValueCallback<Uri> mUploadMessage; private final static int FILECHOOSER_RESULTCODE = 1; public static final int INPUT_FILE_REQUEST_CODE = 1; public static final String EXTRA_FROM_NOTIFICATION = "EXTRA_FROM_NOTIFICATION"; LocationManager locationManager; LocationListener locationListener; private SwipeRefreshLayout mSwipeRefreshLayout; private ValueCallback<Uri[]> mFilePathCallback; private String mCameraPhotoPath; private static final int SELECT_PICTURE = 1; String imgPath, fileName, encodedString; RequestParams params = new RequestParams(); // @Override // protected void onActivityResult(int requestCode, int resultCode, // Intent intent) { // if (requestCode == FILECHOOSER_RESULTCODE) { // if (null == mUploadMessage) return; // Uri result = intent == null || resultCode != RESULT_OK ? null // : intent.getData(); // mUploadMessage.onReceiveValue(result); // mUploadMessage = null; // // } // } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) { super.onActivityResult(requestCode, resultCode, data); return; } Uri[] results = null; // Check that the response is a good one if (resultCode == Activity.RESULT_OK) { if (data == null) { // If there is not data, then we may have taken a photo if (mCameraPhotoPath != null) { results = new Uri[] { Uri.parse(mCameraPhotoPath) }; } } else { String dataString = data.getDataString(); if (dataString != null) { results = new Uri[] { Uri.parse(dataString) }; } } } mFilePathCallback.onReceiveValue(results); mFilePathCallback = null; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //GPS locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { public void onLocationChanged(Location location) { if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now final int REQUEST_LOCATION = 2; if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION); } } else { locationManager.removeUpdates(this); } } public void onStatusChanged(String string, int integer, Bundle bundle) { } public void onProviderEnabled(String string) { } public void onProviderDisabled(String string) { } }; if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now final int REQUEST_LOCATION = 2; if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION); } } else { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationListener); } int delay = 30000; // delay for 30 sec. int period = 3000000; // repeat every 5.3min. Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now final int REQUEST_LOCATION = 2; if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION); } } else { locationManager.removeUpdates(locationListener); } } }, delay, period); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); Intent mIntent = getIntent(); URL = Constants.SERVER_URL; if (mIntent.hasExtra("url")) { myWebView = null; startActivity(getIntent()); String url = mIntent.getStringExtra("url"); URL = Constants.SERVER_URL + url; } CookieSyncManager.createInstance(this); CookieSyncManager.getInstance().startSync(); myWebView = (WebView) findViewById(R.id.webview); myWebView.getSettings().setGeolocationDatabasePath(this.getFilesDir().getPath()); myWebView.getSettings().setGeolocationEnabled(true); WebSettings webSettings = myWebView.getSettings(); webSettings.setUseWideViewPort(false); if (!DetectConnection.checkInternetConnection(this)) { webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); showNoConnectionDialog(this); } else { webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); } webSettings.setJavaScriptEnabled(true); myWebView.addJavascriptInterface(new webappinterface(this), "android"); webSettings.setLoadWithOverviewMode(true); webSettings.setUseWideViewPort(true); myWebView.setOverScrollMode(View.OVER_SCROLL_NEVER); //location test webSettings.setAppCacheEnabled(true); webSettings.setDatabaseEnabled(true); webSettings.setDomStorageEnabled(true); myWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { CookieSyncManager.getInstance().sync(); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); // Ignore SSL certificate errors } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Uri.parse(url).getHost().equals(Constants.HOST) || Uri.parse(url).getHost().equals(Constants.WWWHOST)) { // This is my web site, so do not override; let my WebView load // the page return false; } // Otherwise, the link is not for a page on my site, so launch // another Activity that handles URLs Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } }); myWebView.setWebChromeClient(new WebChromeClient() { public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); } @Override public void onPermissionRequest(final PermissionRequest request) { Log.d(TAG, "onPermissionRequest"); runOnUiThread(new Runnable() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void run() { if (request.getOrigin().toString().equals("https://apprtc-m.appspot.com/")) { request.grant(request.getResources()); } else { request.deny(); } } }); } public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { // Double check that we don't have any existing callbacks if (mFilePathCallback != null) { mFilePathCallback.onReceiveValue(null); } mFilePathCallback = filePathCallback; // Set up the take picture intent Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath); } catch (IOException ex) { // Error occurred while creating the File Log.e(TAG, "Unable to create Image File", ex); } // Continue only if the File was successfully created if (photoFile != null) { mCameraPhotoPath = "file:" + photoFile.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); } else { takePictureIntent = null; } } // Set up the intent to get an existing image Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType("image/*"); // Set up the intents for the Intent chooser Intent[] intentArray; if (takePictureIntent != null) { intentArray = new Intent[] { takePictureIntent }; } else { intentArray = new Intent[0]; } Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE); return true; } }); // setContentView(myWebView); // myWebView.loadUrl(URL); myWebView.loadUrl(URL); mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // mRegistrationProgressBar.setVisibility(ProgressBar.GONE); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false); } }; //CookieManager mCookieManager = CookieManager.getInstance(); //Boolean hasCookies = mCookieManager.hasCookies(); //while(!hasCookies); if (checkPlayServices()) { // Start IntentService to register this application with GCM. Intent intent = new Intent(this, RegistrationIntentService.class); //intent.putExtra("session", session); startService(intent); } Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true); if (isFirstRun) { //show start activity startActivity(new Intent(MainActivity.this, MyIntro.class)); } //if (!isOnline()) // showNoConnectionDialog(this); getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).commit(); //Pull-to-refresh mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.container); mSwipeRefreshLayout.setOnRefreshListener(this); } @Override protected void onNewIntent(Intent intent) { if (intent.hasExtra("url")) { String url = intent.getStringExtra("url"); // myWebView.loadUrl(Constants.SERVER_URL + url); } } @Override protected void onResume() { super.onResume(); ; LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE)); if (DetectConnection.checkInternetConnection(this)) { // myWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); myWebView.reload(); } if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now final int REQUEST_LOCATION = 2; if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION); } } else { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener); } int delay = 30000; // delay for 30 sec. int period = 3000000; // repeat every 5.3min. Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now final int REQUEST_LOCATION = 2; if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION); } } else { locationManager.removeUpdates(locationListener); } } }, delay, period); } @Override protected void onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver); super.onPause(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now final int REQUEST_LOCATION = 2; if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION); } } else { locationManager.removeUpdates(locationListener); } } private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); return File.createTempFile(imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); } /** * Check the device to make sure it has the Google Play Services APK. If * it doesn't, display a dialog that allows users to download the APK from * the Google Play Store or enable it in the device's system settings. */ private boolean checkPlayServices() { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); int resultCode = apiAvailability.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (apiAvailability.isUserResolvableError(resultCode)) { apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i(TAG, "This device is not supported."); finish(); } return false; } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: // if (myWebView.canGoBack()) { // myWebView.goBack(); // } else { // finish(); // } return true; } } return super.onKeyDown(keyCode, event); } public static void showNoConnectionDialog(Context ctx1) { final Context ctx = ctx1; AlertDialog.Builder builder = new AlertDialog.Builder(ctx, R.style.AlertDialog); builder.setCancelable(true); builder.setMessage(R.string.no_connection); builder.setTitle(R.string.no_connection_title); builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); } }); builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { return; } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { return; } }); builder.show(); } @Override public void onRefresh() { myWebView.reload(); new Handler().postDelayed(new Runnable() { @Override public void run() { mSwipeRefreshLayout.setRefreshing(false); } }, 2000); } class webappinterface { Context mContext; webappinterface(Context c) { mContext = c; } @JavascriptInterface public void opengallary() { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent, SELECT_PICTURE); // intent.setType("image/*"); // intent.setAction(Intent.ACTION_GET_CONTENT); // startActivityForResult(Intent.createChooser(intent, "Select Picture"),SELECT_PICTURE); } @SuppressLint("NewApi") @JavascriptInterface public void uploadImage() { //Toast.makeText(getApplicationContext(),"Path:" + , Toast.LENGTH_LONG).show(); if (imgPath != null && !imgPath.isEmpty()) { Toast.makeText(getApplicationContext(), "Uploading : " + imgPath, Toast.LENGTH_LONG).show(); encodeImagetoString(); } else { Toast.makeText(getApplicationContext(), "You must select image from gallery before you try to upload", Toast.LENGTH_LONG).show(); } } } //AsyncTask is using for background process running public void encodeImagetoString() { new AsyncTask<Void, Void, String>() { protected void onPreExecute() { }; @Override protected String doInBackground(Void... params) { BitmapFactory.Options options = null; options = new BitmapFactory.Options(); options.inSampleSize = 3; Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream); byte[] byte_arr = stream.toByteArray(); encodedString = Base64.encodeToString(byte_arr, 0); return ""; } @Override protected void onPostExecute(String msg) { params.put("image", encodedString); // Trigger Image upload triggerImageUpload(); } }.execute(null, null, null); } public void triggerImageUpload() { makehttpcall(); } //makehttpcall public void makehttpcall() { // prgDialog.setMessage("Invoking Php"); AsyncHttpClient client = new AsyncHttpClient(); // Don't forget to change the address to your address. // http://192.168.1.1/webview/upload_image.php client.post("http://192.168.1.1/webview/upload_image.php", params, new AsyncHttpResponseHandler() { // When the response returned by REST has Http // response code '200' @Override public void onSuccess(String response) { Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show(); } // When the response returned by REST has Http // response code other than '200' such as '404', // '500' or '403' etc @Override public void onFailure(int statusCode, Throwable error, String content) { // When Http response code is '404' if (statusCode == 404) { Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG) .show(); } // When Http response code is '500' else if (statusCode == 500) { Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG) .show(); } // When Http response code other than 404, 500 else { Toast.makeText(getApplicationContext(), "Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : " + statusCode, Toast.LENGTH_LONG).show(); } } }); } }