Java tutorial
/* * Copyright 2016 Lemon Computers Inc. * * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * 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.lemon.lime; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.PaintDrawable; import android.media.MediaPlayer; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.BatteryManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.ClipboardManager; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnKeyListener; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.webkit.DownloadListener; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import android.support.v4.graphics.ColorUtils; import android.webkit.WebIconDatabase; import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks; import com.github.ksoichiro.android.observablescrollview.ObservableWebView; import com.github.ksoichiro.android.observablescrollview.ScrollState; import com.pheelicks.utils.TunnelPlayerWorkaround; import com.pheelicks.visualizer.VisualizerView; import com.pheelicks.visualizer.renderer.BarGraphRenderer; import android.support.v4.widget.SwipeRefreshLayout; import eu.chainfire.libsuperuser.Shell; public class MainActivity extends AppCompatActivity implements ObservableScrollViewCallbacks { private static final int RESULT_SETTINGS = 1; final Activity activity = this; private MediaPlayer mPlayer; private MediaPlayer mSilentPlayer; /* to avoid tunnel player issue */ private VisualizerView mVisualizerView; ObservableWebView mWebView; Window window; public EditText editurl; public ImageView favicon; SwipeRefreshLayout swipeLayout; int level = -1; int night; int lili = 0; boolean lilimode = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getBatteryPercentage(); setContentView(R.layout.activity_main); getSupportActionBar().setDisplayShowCustomEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); mWebView = (ObservableWebView) findViewById(R.id.activity_main_webview); mWebView.setScrollViewCallbacks(this); LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflator.inflate(R.layout.bar, null); getSupportActionBar().setCustomView(v); WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath()); swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipeToRefresh); swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mWebView.reload(); } }); swipeLayout.setColorSchemeResources(R.color.lili, R.color.colorPrimary, R.color.red); window = getWindow(); favicon = (ImageView) findViewById(R.id.favicon); editurl = (EditText) findViewById(R.id.editurl); mWebView.setDownloadListener(new DownloadListener() { public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }); favicon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (lili == 5) { lilimode(); lili = 0; lilimode = true; } else { lili = lili + 1; } } }); editurl.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { if (editurl.getText().toString().contains("file:///")) { filemgr(); } else if (editurl.getText().toString().contains("gaymode")) { gaymode(); } else if (editurl.getText().toString().contains("exitapp")) { finish(); } else if (editurl.getText().toString().contains("light")) { flash(); } if (isconnected()) { if (editurl.getText().toString().contains("http://") || editurl.getText().toString().contains("https://")) { mWebView.loadUrl(editurl.getText().toString()); } else if (editurl.getText().toString().contains(".com") || editurl.getText().toString().contains(".net") || editurl.getText().toString().contains(".org") || editurl.getText().toString().contains(".gov") || editurl.getText().toString().contains(".hu") || editurl.getText().toString().contains(".sk") || editurl.getText().toString().contains(".co.uk") || editurl.getText().toString().contains(".co.in") || editurl.getText().toString().contains(".cn") || editurl.getText().toString().contains(".it") || editurl.getText().toString().contains(".de") || editurl.getText().toString().contains(".aus") || editurl.getText().toString().contains(".hr") || editurl.getText().toString().contains(".cz") || editurl.getText().toString().contains(".xyz") || editurl.getText().toString().contains(".pl") || editurl.getText().toString().contains(".io")) { mWebView.loadUrl("http://" + editurl.getText().toString()); InputMethodManager imm = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editurl.getWindowToken(), 0); } else { mWebView.loadUrl("https://www.google.com/search?q=" + editurl.getText().toString()); InputMethodManager imm = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editurl.getWindowToken(), 0); } } return true; } return false; } return true; } }); // Enable Javascript WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setBuiltInZoomControls(true); webSettings.setDisplayZoomControls(false); webSettings.setSupportMultipleWindows(true); if (isconnected()) { mWebView.loadUrl("http://google.com"); } else { final View coordinatorLayoutView = findViewById(R.id.snackbarPosition); mWebView.loadUrl("file:///android_asset/nonet.html"); Snackbar snackbar = Snackbar.make(coordinatorLayoutView, R.string.offline, Snackbar.LENGTH_LONG); snackbar.show(); } mWebView.setWebChromeClient(new WebChromeClient() { @Override public void onReceivedIcon(WebView mWebView, Bitmap icon) { super.onReceivedIcon(mWebView, icon); favicon.setImageBitmap(icon); } public void onProgressChanged(WebView view, int progress) { activity.setProgress(progress * 100); int a = progress; if (lilimode) { editurl.setText("Liling: " + Integer.toString(a) + "?"); } else editurl.setText("Liming: " + Integer.toString(a) + "%"); if (progress == 100) { editurl.setHint(view.getTitle()); activity.setTitle(view.getTitle()); editurl.setText(view.getUrl()); fav(); //battery if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (level <= 20) { window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setNavigationBarColor(Color.RED); window.setStatusBarColor(Color.RED); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.RED)); } } } } }); mWebView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView mWebView, String url) { swipeLayout.setRefreshing(false); } }); } protected void onResume() { super.onResume(); initTunnelPlayerWorkaround(); init(); } protected void onDestroy() { cleanUp(); super.onDestroy(); } private void init() { mPlayer = MediaPlayer.create(this, R.raw.summer); mPlayer.setLooping(true); if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { getvoicemission(); } else { mVisualizerView = (VisualizerView) findViewById(R.id.visualizerView); mVisualizerView.link(mPlayer); } } private void cleanUp() { if (mPlayer != null) { mPlayer.release(); mPlayer = null; } if (mSilentPlayer != null) { mSilentPlayer.release(); mSilentPlayer = null; } } private void initTunnelPlayerWorkaround() { if (TunnelPlayerWorkaround.isTunnelDecodeEnabled(this)) { mSilentPlayer = TunnelPlayerWorkaround.createSilentMediaPlayer(this); } } private void addBarGraphRenderers() { Paint paint = new Paint(); paint.setStrokeWidth(50f); paint.setAntiAlias(true); paint.setColor(Color.argb(200, 56, 138, 252)); BarGraphRenderer barGraphRendererBottom = new BarGraphRenderer(16, paint, false); mVisualizerView.addRenderer(barGraphRendererBottom); Paint paint2 = new Paint(); paint2.setStrokeWidth(12f); paint2.setAntiAlias(true); paint2.setColor(Color.argb(200, 181, 111, 233)); BarGraphRenderer barGraphRendererTop = new BarGraphRenderer(4, paint2, true); mVisualizerView.addRenderer(barGraphRendererTop); } private boolean isconnected() { boolean haveConnectedWifi = false; boolean haveConnectedMobile = false; ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] netInfo = cm.getAllNetworkInfo(); for (NetworkInfo ni : netInfo) { if (ni.getTypeName().equalsIgnoreCase("WIFI")) if (ni.isConnected()) haveConnectedWifi = true; if (ni.getTypeName().equalsIgnoreCase("MOBILE")) if (ni.isConnected()) haveConnectedMobile = true; } return haveConnectedWifi || haveConnectedMobile; } private static final int VOICE_PERMISSIONS_REQUEST = 1; private static final int STORAGE_PERMISSIONS_REQUEST = 1; public void getstoragepermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) { } requestPermissions(new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, STORAGE_PERMISSIONS_REQUEST); } } } public void getvoicemission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { if (shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)) { } requestPermissions(new String[] { Manifest.permission.RECORD_AUDIO }, VOICE_PERMISSIONS_REQUEST); } } } public void fav() { favicon.setImageBitmap(mWebView.getFavicon()); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { final View coordinatorLayoutView = findViewById(R.id.snackbarPosition); if (requestCode == STORAGE_PERMISSIONS_REQUEST) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Snackbar snackbar = Snackbar.make(coordinatorLayoutView, R.string.grantedperm, Snackbar.LENGTH_LONG); snackbar.show(); } else { Snackbar snackbar = Snackbar.make(coordinatorLayoutView, R.string.deniedperm, Snackbar.LENGTH_LONG); snackbar.show(); } } else if (requestCode == VOICE_PERMISSIONS_REQUEST) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Snackbar snackbar = Snackbar.make(coordinatorLayoutView, R.string.grantedperm, Snackbar.LENGTH_LONG); snackbar.show(); } else { Snackbar snackbar = Snackbar.make(coordinatorLayoutView, R.string.deniedperm, Snackbar.LENGTH_LONG); snackbar.show(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem back = menu.findItem(R.id.back); MenuItem forward = menu.findItem(R.id.forward); if (mWebView.canGoBack()) { back.setEnabled(true); back.getIcon().setAlpha(255); } else { // disabled back.setEnabled(false); back.getIcon().setAlpha(130); } if (mWebView.canGoForward()) { forward.setEnabled(true); forward.getIcon().setAlpha(255); } else { // disabled forward.setEnabled(false); forward.getIcon().setAlpha(130); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mWebView.canGoBack()) { getSupportActionBar().show(); mWebView.goBack(); } else { finish(); } return true; } } return super.onKeyDown(keyCode, event); } @Override public boolean onOptionsItemSelected(MenuItem item) { final View coordinatorLayoutView = findViewById(R.id.snackbarPosition); switch (item.getItemId()) { case R.id.back: mWebView.goBack(); break; case R.id.forward: mWebView.goForward(); break; case R.id.reload: mWebView.reload(); break; case R.id.new_tab: Intent c = new Intent(this, MainActivity.class); startActivityForResult(c, RESULT_SETTINGS); break; case R.id.add_bookmark: Intent book = new Intent(this, BookMarkActivity.class); startActivityForResult(book, RESULT_SETTINGS); break; case R.id.share: String url = mWebView.getUrl().toString(); ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(url); Snackbar snackbar = Snackbar.make(coordinatorLayoutView, R.string.clipboard, Snackbar.LENGTH_LONG); snackbar.show(); break; case R.id.menu_settings: Intent i = new Intent(this, UserSettingActivity.class); startActivityForResult(i, RESULT_SETTINGS); break; case R.id.invert: if (night == 0) { getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.BLACK)); mWebView.setBackgroundColor(Color.parseColor("#000000")); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setNavigationBarColor(Color.BLACK); window.setStatusBarColor(Color.BLACK); } night = 1; } else { getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#7AB317"))); mWebView.setBackgroundColor(Color.TRANSPARENT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setNavigationBarColor(Color.parseColor("#7AB317")); window.setStatusBarColor(Color.parseColor("#7AB317")); } night = 0; } break; case R.id.hide: View decorView = window.getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); getSupportActionBar().hide(); break; case R.id.easteregg: Toast.makeText(this, "( Y )", Toast.LENGTH_SHORT).show(); mPlayer.start(); addBarGraphRenderers(); break; } return true; } private void filemgr() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getstoragepermission(); } else { mWebView.loadUrl(editurl.getText().toString()); } } private void lilimode() { BitmapDrawable bg = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.tiger)); getSupportActionBar().setBackgroundDrawable(bg); mWebView.setBackgroundColor(Color.CYAN); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.setNavigationBarColor(Color.CYAN); window.setStatusBarColor(Color.parseColor("#C3721A")); } final View coordinatorLayoutView = findViewById(R.id.snackbarPosition); Snackbar snackbar = Snackbar.make(coordinatorLayoutView, R.string.lilimode, Snackbar.LENGTH_LONG) .setAction("?", new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder alertadd = new AlertDialog.Builder(MainActivity.this); LayoutInflater factory = LayoutInflater.from(MainActivity.this); final View liliview = factory.inflate(R.layout.lili, null); alertadd.setView(liliview); alertadd.show(); } }); snackbar.getView().setBackgroundColor(Color.parseColor("#03c1c1")); snackbar.show(); } private void flash() { Intent f = new Intent(this, FlashActivity.class); startActivityForResult(f, RESULT_SETTINGS); } private void gaymode() { getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF69B4"))); mWebView.setBackgroundColor(Color.parseColor("#FF69B4")); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.setNavigationBarColor(Color.parseColor("#FF69B4")); window.setStatusBarColor(Color.parseColor("#FF69B4")); } } private void getBatteryPercentage() { BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { context.unregisterReceiver(this); int currentLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); if (currentLevel >= 0 && scale > 0) { level = (currentLevel * 100) / scale; } } }; IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(batteryLevelReceiver, batteryLevelFilter); } @Override public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) { } @Override public void onDownMotionEvent() { } @Override public void onUpOrCancelMotionEvent(ScrollState scrollState) { ActionBar ab = getSupportActionBar(); if (ab == null) { return; } if (scrollState == ScrollState.UP) { if (ab.isShowing()) { ab.hide(); } } else if (scrollState == ScrollState.DOWN) { if (!ab.isShowing()) { ab.show(); } } } }