Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Monday, November 18, 2019

app-debug.apk test using emulator avd command prompt

START EMULATOR

C:\Users\home>emulator -list-avds
Pixel_XL_API_22

C:\Users\home>emulator -avd Pixel_XL_API_22
emulator: WARNING: encryption is off
Warning: Quick Boot / Snapshots not supported on this machine. A CPU with EPT +
UG features is currently needed. We will address this in a future release.
emulator: WARNING: Not all modern X86 virtualization features supported, which i
ntroduces problems with slowdown when running Android on multicore vCPUs. Settin
g AVD to run with 1 vCPU core only.
emulator: WARNING: Your GPU drivers may have a bug. Switching to software render
ing.
HAX is working and emulator runs in fast virt mode.


RUN APK on EMULATOR

C:\Users\home>adb devices
List of devices attached
emulator-5554   device


C:\Users\home>adb -e install -r D:\app-debug.apk
Performing Push Install
D:\app-debug.apk: 1 file pushed. 35.9 MB/s (19761823 bytes in 0.525s)
        pkg: /data/local/tmp/app-debug.apk
Success

C:\Users\home>

Thursday, November 7, 2019

Security with HTTPS and SSL socket client creating with Trusted Certificate, KeyStore, bks type

private fun createHttpClient(): HttpClient {
        var httpClient: HttpClient? = null        try {
            val is_unsafe = AppConfig.current.getApiItem("unsafe").toBoolean()
            val requestConfig = RequestConfig.custom().setCircularRedirectsAllowed(true).build()

            var trustAllCerts = arrayOf<TrustManager>()
            val sslContext = SSLContext.getInstance(ConstVariables.SSLContext_TLS)
            if (is_unsafe) {
                trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                    override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
                    override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
                    override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
                })
                sslContext.init(null, trustAllCerts, SecureRandom())
            } else {
                var keyStore = App.getTrustedKeyStore()
                var trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
                trustManagerFactory.init(keyStore)
//                val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())//                keyManagerFactory.init(keyStore, null)                sslContext.init(null, trustManagerFactory.trustManagers, SecureRandom())
            }

            var sslsf = SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)
            var socketFactoryRegistry = RegistryBuilder.create<ConnectionSocketFactory>()
                    .register("https", sslsf).build()//.register("http", PlainConnectionSocketFactory())
            var connectionManager = BasicHttpClientConnectionManager(socketFactoryRegistry)
            httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
                    .setConnectionManager(connectionManager).build()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return httpClient as HttpClient
    }
**********************************************************************
private fun makeSocket(roomInfo: JSONObject): Socket? {
        if (mSocket != null)
            return mSocket        else {
            try {
                val is_unsafe = AppConfig.current.getApiItem("unsafe").toBoolean()
                val bot_timeout = AppConfig.current.getApiItem("bot_timeout").toLong()

                var trustAllCerts = arrayOf<TrustManager>()
                val sslContext = SSLContext.getInstance(ConstVariables.SSLContext_TLS)
                var trustManager: X509TrustManager? = null                if (is_unsafe) {
                    trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                        override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
                        override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
                        override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
                    })
                    sslContext.init(null, trustAllCerts, SecureRandom())

                    trustManager = trustAllCerts.get(0) as X509TrustManager
                } else {
                    var keyStore = App.getTrustedKeyStore()
                    var trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
                    trustManagerFactory.init(keyStore)
//                    val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())//                    keyManagerFactory.init(keyStore, null)                    sslContext.init(null, trustManagerFactory.trustManagers, SecureRandom())

                    trustManager = trustManagerFactory.trustManagers.get(0) as X509TrustManager
                }

                //val trustManager = trustManagerFactory.trustManagers.get(0) as X509TrustManager                val okHttpClient = OkHttpClient.Builder().hostnameVerifier(NoopHostnameVerifier.INSTANCE)
                        .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
                        .cookieJar(makeCookieJar())
                        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(bot_timeout, TimeUnit.SECONDS).writeTimeout(bot_timeout, TimeUnit.SECONDS)
                        .build()

                val options = IO.Options()
                //options.query = ("authtoken=" + AppSharedPrefrence.getString(this, App..AUTH_TOKEN))                options.forceNew = AppConfig.current.getApiItem("bot_forceNew").toBoolean()
                options.secure = AppConfig.current.getApiItem("bot_secure").toBoolean()
                options.callFactory = okHttpClient
                options.webSocketFactory = okHttpClient
                options.transports = arrayOf(WebSocket.NAME, Polling.NAME)
                val botUrl = UrlHelper.botUrl("room-" + roomInfo.getInt("id"))
                mSocket = IO.socket(botUrl, options)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return mSocket    }
**********************************************************************
fun getTrustedKeyStore(): KeyStore {
    if (trusted != null) return trusted as KeyStore
    val caInput = resource.openRawResource(R.raw.server)
    val cf = CertificateFactory.getInstance("X.509")
    val ca: Certificate
    try {
        ca = cf.generateCertificate(caInput)
        System.out.println("ca=" + (ca as X509Certificate).getSubjectDN())
    } finally {
        caInput.close()
    }

    // Create a KeyStore containing our trusted CAs    val keyStoreType = KeyStore.getDefaultType()
    val keyStore = KeyStore.getInstance(keyStoreType)
    keyStore.load(null, null)
    keyStore.setCertificateEntry("ca", ca)
    if (keyStoreType == ConstVariables.KeyStore_BKS) {
        return keyStore
    } else {
        var host = AppConfig.current.getApiItem("host")
        var hi = host.indexOf(':')
        var hip = host.substring(0, hi)
        var hips = hip.split('.')
        var ks = "ks_" + hips[2] + "_" + hips[3]
        var rid = ResourceHelper.getResourceId(ks, "raw")
        trusted = KeyStore.getInstance(ConstVariables.KeyStore_BKS)
        var ins = if (AppConfig.isApiRunatDevMode()) resource.openRawResource(rid)
        else resource.openRawResource(R.raw.key_store)//key_store.bks        try {
            trusted?.load(ins, null)
        } finally {
            ins.close()
            return trusted as KeyStore
        }
    }
}

Hide automatically the navigation bar in code behind using custom library with OnSystemUiVisibilityChangeListener

package mn.ho.mypoker.libraries.views

import android.os.Handler
import android.view.View
import android.view.Window


class SystemUiVisibilityHider(w: Window) : View.OnSystemUiVisibilityChangeListener {
    private var window: Window = w
    private var isFlagHideSystemUI = false    private var flagHideSystemUI = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE            or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION            or View.SYSTEM_UI_FLAG_FULLSCREEN            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)

    init {
        this.window.decorView.setOnSystemUiVisibilityChangeListener(this)
    }

    override fun onSystemUiVisibilityChange(visibility: Int) {
        if (this.window.decorView.systemUiVisibility != flagHideSystemUI) {
            Handler().postDelayed({                isFlagHideSystemUI = false            }, 1000)
        }
    }

    fun run() {
        if (this.window.decorView.systemUiVisibility != flagHideSystemUI) {
            isFlagHideSystemUI = true            this.window.decorView.systemUiVisibility = flagHideSystemUI        }
    }
}

on Activity

override fun onTouchEvent(event: MotionEvent?): Boolean {
    sysNavHider?.run()
    return super.onTouchEvent(event)
}

how to install app-debug.apk file into android phone using command prompt shell

#-t is test only
#-r is reinstall
adb devices
List of devices attached
06157df6848f6a14        device
LGMS55017965c0d device
f89c9b8f        device

adb push app-debug.apk /tmp/
pm install /tmp/app-debug.apk
#if Failure [INSTALL_FAILED_INVALID_URI]

#then use android phone shell command
adb -s 06157df6848f6a14 shell
pm install -t -r /sdcard/Download/app-debug.apk

or using Terminal Emulator App


Friday, July 26, 2019

boroo\.AndroidStudio3.4\config\studio64.exe.vmoptions

-server
-Xms1024m
-Xmx2048m
-XX:MaxPermSize=250m
-XX:ReservedCodeCacheSize=240m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Djdk.http.auth.tunneling.disabledSchemes=""
-Djna.nosys=true
-Djna.boot.library.path=
-da

Saturday, December 29, 2018

android kotlin ArrayAdapter withen JSONObject itemdata

private inner class StableArrayAdapter(context: Context, viewResourceId: Int)
    : ArrayAdapter<JSONObject>(context, viewResourceId) {

    fun addItems(items: JSONArray) {
        for (i in 0 until items.length()) {
            val item = items.getJSONObject(i)
            this.add(item)
        }
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var retView: View? = null        if (convertView == null) {
            retView = LayoutInflater.from(getContext()).inflate(R.layout.main_row_item, parent, false)
        } else {
            retView = convertView
        }
        val item = getItem(position) as JSONObject
        retView!!.tag = item

        if (item.optBoolean("is_denied"))
            retView!!.icon_state.setBackgroundResource(R.drawable.bg_oval_odo_maroon)
        else {
            if (item.optBoolean("is_received"))
                retView!!.icon_state.setBackgroundResource(R.drawable.bg_oval_disable_blue)
            else {
                if (item.optBoolean("is_approved"))
                    retView!!.icon_state.setBackgroundResource(R.drawable.bg_oval_odo_orange)
                else {
                    if (item.optBoolean("is_sent"))
                        retView!!.icon_state.setBackgroundResource(R.drawable.bg_oval_active_blue)
                    else                        retView!!.icon_state.visibility = View.GONE                }
            }
        }

        val dateStr = item.getString("created_at")
        retView.tv_datetime.setText(AppHelper.formatJsonDate(dateStr))

        val toc = item.getJSONObject("toc")
        val tob = item.getJSONObject("tob")
        retView.tv_name.setText(toc.getString("name") + " / " + tob.getString("name"))
        retView.tv_descr.setText("№ " + item.getString("order_number") + " - " + item.getString("order_name"))

        retView.setOnClickListener { view ->            itemClick(view)
        }        return retView!!
    }

    fun itemClick(view: View) {
        val item = view.tag as JSONObject

        val args = Bundle()
        args.putString(ArgumentPassKeys.ARG_JSON_OBJECT, item.toString())

        val intent = Intent(_context, EventsActivity::class.java)
        intent.putExtras(args)
        _activity!!.startActivityForResult(intent, ActivityPassCodes.ITEM_EDIT)
    }
}

Thursday, May 17, 2018

android What is the difference between GridView for dynamicallty add item vs GridLayout for statically view

<GridLayout    android:layout_width="match_parent"    android:layout_height="0dp"    android:layout_weight="2"    android:alignmentMode="alignBounds"    android:rowCount="2"    android:columnCount="2"    android:columnOrderPreserved="false"    android:padding="@dimen/gap16"    android:orientation="horizontal">

    <android.support.v7.widget.CardView        android:layout_columnWeight="1"        android:layout_rowWeight="1"        android:layout_gravity="fill"        android:layout_column="0"        android:layout_row="0"        android:layout_margin="@dimen/gap16"        app:cardCornerRadius="@dimen/gap3"        app:cardElevation="@dimen/gap3">

        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_gravity="fill"            android:orientation="vertical">

            <Button                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:text="button 1"                android:background="@color/colorOdoOrange"                android:textColor="@color/colorWhite" />
        </LinearLayout>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView        android:layout_columnWeight="1"        android:layout_rowWeight="1"        android:layout_gravity="fill"        android:layout_column="1"        android:layout_row="1"        android:layout_margin="@dimen/gap16"        app:cardCornerRadius="@dimen/gap3"        app:cardElevation="@dimen/gap16">

        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_gravity="fill"            android:orientation="vertical">

            <Button                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:text="button 2"                android:background="@color/colorOdoOrange"                android:textColor="@color/colorWhite" />
        </LinearLayout>
    </android.support.v7.widget.CardView>

</GridLayout>


VS


<mn.odo.ordersystem.components.OdoGridView    android:id="@+id/lv_goods_images"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_marginTop="@dimen/gap16"    android:layout_marginBottom="@dimen/gap16"    android:isScrollContainer="false"    android:columnWidth="0dp"    android:gravity="center"    android:numColumns="5"    android:stretchMode="columnWidth"    android:horizontalSpacing="@dimen/gap0"    android:verticalSpacing="@dimen/gap0" />


gridview item:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:orientation="vertical">

    <Button        android:id="@+id/item_image"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="@color/colorBgSubTitleBlue"        android:text="button 0" />

</LinearLayout>

Sunday, May 13, 2018

android kotlin tablayout child tab ViewGroup.MarginLayoutParams setMargins, setPadding with padding dp to px

val slidingTabStrip = tabs.getChildAt(0) as ViewGroup
for (i in 0 until slidingTabStrip.childCount - 1) {
    val v = slidingTabStrip.getChildAt(i)
    val p = v.getLayoutParams() as ViewGroup.MarginLayoutParams
    p.setMargins(0, 0, 0, 0)

    val scale = resources.displayMetrics.density
    var pxl = resources.getDimensionPixelSize(R.dimen.gap1)
    val padding_in_dp = 3    val padding_in_px = (padding_in_dp * scale + 0.5f).toInt()
    v.setPadding(pxl, pxl, pxl, pxl)
}

Saturday, May 12, 2018

android activity theme customize colors

<activity    android:name=".LoginActivity"    
android:label="@string/app_name"    
android:screenOrientation="portrait"    
android:theme="@style/LoginTheme.NoActionBar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>


<!-- Login application theme. --><style name="LoginTheme" 
parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="LoginTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>


  • colorPrimary – The color of the app bar.
  • colorPrimaryDark – The color of the status bar and contextual app bars; this is normally a dark version of colorPrimary.
  • colorAccent – The color of UI controls such as check boxes, radio buttons, and edit text boxes.
  • windowBackground – The color of the screen background.
  • textColorPrimary – The color of UI text in the app bar.
  • statusBarColor – The color of the status bar.
  • navigationBarColor – The color of the navigation bar.
you can use following link to setup your style.

Monday, April 30, 2018

android check whether internet is available or not.

//check whether internet is available or not.
    public boolean isReachable(String address, int port, int timeoutMs) {
        try {
            Socket sock = new Socket();
            SocketAddress sockaddr = new InetSocketAddress(address, port);

            sock.connect(sockaddr, timeoutMs); // this will block no more than timeoutMs
            sock.close();

            return true;

        } catch (IOException e) { return false; }
    }

Sunday, April 26, 2015

standard SearchView in Action Bar android

@Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            App.config.init(R.xml.app_config);

            //initActionBarCommands();
            //historySet(new HomeFragment(), R.id.frame_container, null);
        }
    }

    @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_main, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        ComponentName componentName = new ComponentName(getApplicationContext(), SearchResultsActivity.class);
        SearchableInfo searchableInfo = searchManager.getSearchableInfo(componentName);
        if (searchView != null) {
            searchView.setSearchableInfo(searchableInfo);
        }

        return true;
    }


in xml/searchable.xml


<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/hint_search"
    android:includeInGlobalSearch="false"/>


in AndroidManifect.xml


<activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SearchResultsActivity" android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable"
                android:value=".SearchResultActivity" />

        </activity>

Monday, February 9, 2015

how to fix org.gradle.tooling.buildexception: could not run build action using gradle distribution in netbeans

On Windows I tried below two but nothing worked.
Java Control Panel / Java / Java Runtime Settings / View / User / Runtime Parameters -Dfile.encoding=UTF-8
set JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8
Java Console still prints out
file.encoding = MS949

Environment Variables may be? –  R.J Mar 21 '13 at 7:28
    
What is about running jconsole -J-Dfile.encoding=UTF-8 ? –  PeterMmm Mar 21 '13 at 8:00

2 Answers

Maybe you nedd a global JVM option:
try to add JAVA_OPTSto you windows environment.
set JAVA_OPTS=-Dfile.encoding=UTF-8 %JAVA_OPTS%

Wednesday, February 4, 2015

android application exit with Activity.finish() when back pressed

@Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setMessage(R.string.system_exit_confirm_message)
                .setCancelable(false)
                .setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        finish();
                    }
                })
                .setNegativeButton(R.string.btn_no, null)
                .show();
    }

Sunday, January 18, 2015

android custom textview with round stroke drawing

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.TextView;

import com.hiimeloyun.android.R;

/**
 *
 * @author boroo
 */
public class StrokeTextView extends TextView {

    private final int strokeColor;
    private final float strokeWidth;

    TextPaint paint = new TextPaint();

    public StrokeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.StrokeStyleable, 0, 0);
        strokeWidth = a.getDimension(R.styleable.StrokeStyleable_strokeWidth, 10);
        strokeColor = a.getColor(R.styleable.StrokeStyleable_strokeColor, Color.BLACK);
    }

    // overridden methods
    @Override
    protected void onDraw(Canvas canvas) {
        final ColorStateList textColor = getTextColors();
      
        paint = this.getPaint();

        paint.setStyle(Style.STROKE);
        paint.setStrokeJoin(Join.ROUND);
        paint.setStrokeMiter(10);
        this.setTextColor(strokeColor);
        paint.setStrokeWidth(strokeWidth);

        super.onDraw(canvas);
        paint.setStyle(Style.FILL);

        setTextColor(textColor);
        super.onDraw(canvas);
    }
}