com.jwetherell.quick_response_code.EncoderActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.jwetherell.quick_response_code.EncoderActivity.java

Source

/*
 * 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.jwetherell.quick_response_code;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Hashtable;

import org.w3c.dom.Text;

import android.R.color;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.proyecto.avansis.miwifimovistar.AVActivateWpsActivity;
import com.proyecto.avansis.miwifimovistar.MainActivity;
import com.proyecto.avansis.miwifimovistar.R;
import com.proyecto.avansis.miwifimovistar.dialogs.PopupDialog1;
import com.proyecto.avansis.miwifimovistar.hito2.TutorialActivity;
import com.proyecto.avansis.miwifimovistar.utils.Statistics;
import com.proyecto.avansis.miwifimovistar.utils.TAGS;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.jwetherell.quick_response_code.data.Contents;
import com.jwetherell.quick_response_code.qrcode.QRCodeEncoder;

/**
 * Example Encoder Activity.
 *
 * @author Justin Wetherell (phishman3579@gmail.com)
 */
@SuppressLint("NewApi")
public final class EncoderActivity extends FragmentActivity {

    private static final String TAG = EncoderActivity.class.getSimpleName();

    private SharedPreferences settings;

    private TextView textoSsid;
    private TextView textoPassword;
    private TextView descripcion;
    private ImageView icon;

    private ImageView viewCode;

    private String ssidFull = "";
    private String pskFull = "";

    private String ssidSettings = null;
    private String pskSettings = null;
    private String cifradoSettings = null;
    private ProgressDialog loadingDialog;

    private String cifradoQR = "";
    private String string = "";

    private Bitmap bm;

    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.encoder);

        // Action bar icon back
        getActionBar().setDisplayHomeAsUpEnabled(true);
        //getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        com.ranorex.android.RanorexAndroidAutomation.Hook(this);
        // Get text views
        textoSsid = (TextView) findViewById(R.id.ssid);
        textoPassword = (TextView) findViewById(R.id.password);
        descripcion = (TextView) findViewById(R.id.descripcion);
        icon = (ImageView) findViewById(R.id.icon);
        //textoCifrado = (TextView) findViewById(R.id.cifrado);

        settings = getSharedPreferences(MainActivity.PREFS, 0);

        // if(settings.contains("connected_wifi_5ghz") && settings.getBoolean("connected_wifi_5ghz", false))
        //      descripcion.setText("");

        final ProgressDialog dialog = new ProgressDialog(EncoderActivity.this);

        dialog.setMessage("Generando Qr...");
        dialog.show();
        dialog.setCancelable(false);

        try {

            if (settings.contains("ssid") && settings.contains("password1")) {
                // Get ssid, psk and encrypted of settings.

                if (!getIntent().getBooleanExtra("is_5ghz", false)) // Network 2.4 GHz.
                {
                    cifradoSettings = settings.getString("cifrado", "WPA");
                    ssidSettings = settings.getString("ssid", "");
                    pskSettings = settings.getString("password1", "");
                    if (settings.contains("connected_wifi_5ghz")
                            && !settings.getBoolean("connected_wifi_5ghz", false)
                            || !settings.contains("connected_wifi_5ghz")) {
                        descripcion.setVisibility(View.VISIBLE);
                    }
                } else // Network 5 GHz.
                {
                    cifradoSettings = settings.getString("cifrado5ghz", "WPA");
                    ssidSettings = settings.getString("ssid5ghz", "");
                    pskSettings = settings.getString("password5ghz", "");
                    icon.setImageResource(R.drawable.wifiplus120);
                    ((TextView) findViewById(R.id.textView1)).setText("WifiPlus");
                    if (settings.contains("connected_wifi_5ghz")
                            && settings.getBoolean("connected_wifi_5ghz", false)) {
                        descripcion.setVisibility(View.VISIBLE);
                    }
                }

                ssidFull = ssidSettings;
                pskFull = pskSettings;

                if (cifradoSettings.contains("WPA")) {
                    cifradoQR = "WPA";
                    string = "WIFI:T:" + cifradoQR + ";S:" + ssidSettings + ";P:" + pskSettings + ";;";
                } else if (cifradoSettings.contains("abierta")) {
                    cifradoQR = "nopass";
                    string = "WIFI:T:" + cifradoQR + ";S:" + ssidSettings + ";;";
                } else if (cifradoSettings.contains("WEP")) {
                    cifradoQR = "WEP";
                    string = "WIFI:T:" + cifradoQR + ";S:" + ssidSettings + ";P:" + pskSettings + ";;";
                }

                // Update texts
                textoSsid.setText(ssidSettings);

                try {
                    if (pskSettings.length() > 39)
                        pskSettings = ellipsis(pskSettings, 39);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (pskSettings.equalsIgnoreCase("sin password") || pskSettings.equalsIgnoreCase(""))
                    pskSettings = "Sin password";

                textoPassword.setText(pskSettings);

            }

        } catch (IllegalArgumentException e) {
            Log.e(TAG, "Could not encode barcode", e);
        }

        new AsyncTask<String, Integer, Bitmap>() {

            @Override
            protected Bitmap doInBackground(String... params) {
                QRCodeEncoder qrCodeEncoder = null;
                // This assumes the view is full screen, which is a good assumption
                WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
                Display display = manager.getDefaultDisplay();
                int width = display.getWidth();
                int height = display.getHeight();
                int smallerDimension = width < height ? width : height;
                smallerDimension = smallerDimension * 7 / 8;

                try {
                    qrCodeEncoder = new QRCodeEncoder(string, null, Contents.Type.TEXT,
                            BarcodeFormat.QR_CODE.toString(), smallerDimension);
                    Hashtable hints = new Hashtable();
                    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
                    QRCodeWriter qrcw = new QRCodeWriter();
                    BitMatrix matrix = qrcw.encode(string, BarcodeFormat.QR_CODE, width, height, hints);
                    bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                    for (int y = 0; y < matrix.getHeight(); y++) {
                        for (int x = 0; x < matrix.getWidth(); x++) {
                            if (!matrix.get(x, y))
                                bm.setPixel(x, y, Color.WHITE);
                            else
                                bm.setPixel(x, y, Color.BLACK);
                        }
                    }
                } catch (WriterException we) {
                    we.printStackTrace();
                    Log.e(TAG, "Could not encode barcode", we);
                }

                return bm;
            }

            protected void onPostExecute(Bitmap bitmap) {
                if (bitmap != null) {
                    viewCode = (ImageView) findViewById(R.id.image_view);
                    viewCode.setImageBitmap(bitmap);//bitmap);
                    dialog.dismiss();
                } else {
                    Toast.makeText(EncoderActivity.this, "Problema al generar Qr", Toast.LENGTH_LONG).show();
                }
            }
        }.execute();

        if (bm != null) {
            dialog.dismiss();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        com.ranorex.android.RanorexAndroidAutomation.UnHook(this);
    }

    @Override
    public boolean dispatchKeyEvent(android.view.KeyEvent event) {
        com.ranorex.android.RanorexAndroidAutomation.Key(event);
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.menu_contextual_invitar, menu);

        if (settings.getString("modelo", "").equals("amper")) {
            menu.getItem(1).setVisible(false);
        }

        return true;
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        Statistics.getInstance(EncoderActivity.this).click();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.btnshare:
            OnClickShare(null);
            return true;
        case android.R.id.home:
            onBackPressed();
            return true;
        case R.id.empty:
            Statistics.getInstance(EncoderActivity.this).click();
            View menuItemView = findViewById(R.id.empty);
            PopupMenu popupMenu = new PopupMenu(this, menuItemView);
            popupMenu.inflate(R.menu.menu_contextual_wps);
            for (int i = 0; i < popupMenu.getMenu().size(); i++) {
                MenuItem itemMenu = popupMenu.getMenu().getItem(i);
                SpannableString spanString = new SpannableString(
                        popupMenu.getMenu().getItem(i).getTitle().toString());
                spanString.setSpan(new ForegroundColorSpan(Color.BLACK), 0, spanString.length(), 0);
                itemMenu.setTitle(spanString);
            }
            popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    Statistics.getInstance(EncoderActivity.this).click();
                    // TODO Auto-generated method stub
                    switch (item.getItemId()) {
                    case R.id.wps:
                        Statistics.getInstance(EncoderActivity.this).sendStatistics(TAGS.TAG_31);
                        Intent mIntent = new Intent(EncoderActivity.this, AVActivateWpsActivity.class);
                        mIntent.putExtra("is_5ghz", getIntent().getBooleanExtra("is_5ghz", false));
                        startActivity(mIntent);
                        break;

                    default:
                        break;
                    }

                    return false;
                }
            });
            popupMenu.show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    public void OnClickHelp1(View view) {
        Statistics.getInstance(EncoderActivity.this).click();
        CharSequence title = getResources().getText(R.string.popup_check_info_QR_title);
        CharSequence content = getResources().getText(R.string.popup_check_info_QR_content);
        final PopupDialog1 popupDialog = new PopupDialog1(this, title, content, false, true);
        //        popupDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "Aceptar", new DialogInterface.OnClickListener()
        //        {   
        //           @Override
        //           public void onClick(DialogInterface dialog, int which) 
        //           {
        //              popupDialog.dismiss();
        //           }
        //        });
        popupDialog.show();
    }

    private static int typeShare = 2;

    public void OnClickShare(View view) {
        Statistics.getInstance(EncoderActivity.this).click();

        String message = "";
        message += "\n" + "Nombre Wifi: " + ssidFull;
        message += "\n" + "Clave Wifi: " + pskFull;

        switch (typeShare) {
        case 0: //text

            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, message);
            sendIntent.setType("text/plain");
            startActivity(Intent.createChooser(sendIntent, "enviar texto"));

            //         typeShare++;
            break;

        case 1:
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(viewCode));
            shareIntent.setType("image/jpeg");
            startActivity(Intent.createChooser(shareIntent, "enviar imagen"));

            //         typeShare++;
            break;

        case 2:

            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("*/*");
            share.putExtra(Intent.EXTRA_TEXT, message);
            share.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(viewCode));
            startActivity(Intent.createChooser(share, "Enviar datos de Mi Wifi"));

            //         typeShare = 0;
            break;

        default:
            break;
        }

    }

    // Returns the URI path to the Bitmap displayed in specified ImageView
    public Uri getLocalBitmapUri(ImageView imageView) {
        // Extract Bitmap from ImageView drawable
        Drawable drawable = imageView.getDrawable();
        Bitmap bmp = null;
        if (drawable instanceof BitmapDrawable) {
            bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        } else {
            return null;
        }
        // Store image to default external storage directory
        Uri bmpUri = null;
        try {
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                    "miwifiQR_" + System.currentTimeMillis() + ".png");
            file.getParentFile().mkdirs();
            FileOutputStream out = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();
            bmpUri = Uri.fromFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmpUri;
    }

    @SuppressLint("NewApi")
    public OnClickListener onclickPopUpMenu(MenuItem item) {
        //Creating the instance of PopupMenu
        PopupMenu popup = new PopupMenu(EncoderActivity.this, item.getActionView());
        //Inflating the Popup using xml file
        popup.getMenuInflater().inflate(R.menu.menu_contextual_wps, popup.getMenu());

        //registering popup with OnMenuItemClickListener
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(EncoderActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        popup.show(); //showing popup menu
        return null;

    }

    public static String ellipsis(final String text, int length) {
        return text.substring(0, length - 1) + "...";
    }
}