Blog

  • How to open activity by Android WebView hyperlink click or How to handle hyperlink click in Android WebView

    How to open activity by Android WebView hyperlink click or How to handle hyperlink click in Android WebView

    Case 1:
    I have Android WebView with some HTML content. I need to open activity when user click on some hyperlink.

    Case 2:
    I have Android WebView with some HTML content. I need to do something when user click some hyperlink.

    HOW TO DO THIS.

    Below you can download source code of this sample Android project

    1. To do this your WebView must have your custom WebViewClient
    2. Your Android WebView HTML content must have specific hyperlinks.

    Lets see source code of Activity:

    package com.hrupin.sample.webviewintent;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    
    public class SendIntentByHyperlinkClickActivity extends Activity {
        private WebView webView1;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            webView1 = (WebView) findViewById(R.id.webView1);
            String summary = "<html><head><title>Title of the document</title></head><body><h1><a href=\"hrupin://second_activity\">LINK to second activity</a></h1><h1><a href=\"http://www.google.com/\">Link to GOOGLE.COM</a></h1></body></html>";
            webView1.loadData(summary, "text/html", null);
            webView1.setWebViewClient(new MyWebViewClient(this));
        }
    }

    The sourcecode of MyWebViewClient must be something like this:
    Pay attantion in shouldOverrideUrlLoading method.

    package com.hrupin.sample.webviewintent;
    
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.view.KeyEvent;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    
    public class MyWebViewClient extends WebViewClient {
    
        private Context context;
    
        public MyWebViewClient(Context context) {
            this.context = context;
        }
    
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.equals("hrupin://second_activity")) {
                Intent i = new Intent(context, SecondActivity.class);
                context.startActivity(i);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

    That’s all.

    Here you can download source code of sample project to see sample of usage.

    Download it from github
  • How to transfer java class between Android Activities

    How to transfer java class between Android Activities

    There are a lot of ways transferring complex data between Android activities. Lets talking about couple of they. I going to talking about ways which used Bundle as data container.

    1. FIRST. Pascelable interface

    Bundle can contain java class which implemented Parcelable interface. Your class must implement this interface. After that bundle can contains this class.

    2. SECOND. Put as JSON string
    In some cases I transfer data between activities as JSON string.

    This is not finished list of techniques. There are couple of then.

  • How to use custom Truetype font in Android UI or playing with TypeFaces

    How to use custom Truetype font in Android UI or playing with TypeFaces

    Here is the sample of usage:

    Below you can download source code of this sample Android project

    To use custom Truetype font in your Android UI you need.
    1. Download *.TTF file with font.
    2. put this file in assets project’s dir.
    3. You need read this font from assets dir:

    Typeface typeFace = Typeface.createFromAsset(context.getAssets(), "YOUR_FONT.ttf");

    4. set TypeFace for your UI element. In my case it is TextView.

    textView.setTypeface(typeFace);

    Also it works for Button, EditText, etc.
    Full source code of activity:

    package com.hrupin.sample.customfont;
    
    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Typeface;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class CustomFontInAndroidActivity extends Activity {
        private static Typeface typeFace = null;
        private TextView textView;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            initTypeFace(this);
            textView = (TextView) findViewById(R.id.text);
            textView.setText("Hello, my name is Igor Khrupin.\n\n I can help you in Android development.\n\n Contact me:\n www.hrupin.com");
            textView.setTypeface(typeFace);
        }
    
        public static void initTypeFace(Context context) {
            if (typeFace == null) {
                try {
                    typeFace = Typeface.createFromAsset(context.getAssets(), "AeroviasBrasilNF.ttf");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    Here you can download source code of this sample Android project.

    Download it from github
  • How to create custom Vertical or Horizontal Scrollbar for ListView, ScrollView, etc. in Android

    How to create custom Vertical or Horizontal Scrollbar for ListView, ScrollView, etc. in Android

    Here is the screenshot of my custom Android scrollbar.

    Below you can download source code of this sample Android project

    How do the same.

    It is so simple. To make custom scrollbar for ListView or ScrollView, etc. you need set android:scrollbarThumbVertical or android:scrollbarThumbVertical for in screen layout. Example:

    <listview android:id="@+id/listView1" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        android:scrollbarthumbvertical="@drawable/thumb"/>

    Also it can be used with ScrollView, etc.

    Here you can download source code of sample Android project.

    Download it from github
  • How to make a transparent WebView in Android

    How to make a transparent WebView in Android

    Today one of my subscribers (@prasad) ask me: “how to make a transparent webview behind a gridview.”

    I don’t have complete example for it, but this info might help you.

    Do do transparent WebView I create this layout:

    <?xml version="1.0" encoding="UTF-8"?>
    <!--?xml version="1.0" encoding="utf-8"?-->
    <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:orientation="vertical" 
        android:background="#ff0000">
        
       <webview android:id="@+id/webView1" 
                android:layout_width="match_parent" 
                android:layout_height="match_parent" />
    </linearlayout>

    Notice, that backgroung behind WebView is RED

    And here I have sourcecode of Activity:

    package com.hrupin.transparent_webview;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.webkit.WebView;
    
    public class Transparent_webviewActivity extends Activity {
        private WebView webview;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            webview = (WebView) findViewById(R.id.webView1);
            // Here is I make transparent background for WebView
            webview.setBackgroundColor(0x00000000);
            String summary = "<h1>The content of the document......</h1>";
            webview.loadData(summary, "text/html", null);
        }
    }

    That’s all.
    It works for me on Android 2.3.3 (Gingerbread). Device is HTC Desire.

  • How to detect when mobile phone received the SMS Message on Android.

    How to detect when mobile phone received the SMS Message on Android.

    To receive SMS messages you need to create BroadcastReceiver for it.

    Below you can download source code of sample Android project

    Here is SmsBroadcastReceiver.java

    package com.hrupin.sample.sms;
    
    import android.content.BroadcastReceiver;
    import android.content.ContentValues;
    import android.content.Context;
    import android.content.Intent;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.telephony.SmsMessage;
    import android.util.Log;
    import android.widget.Toast;
    
    public class SmsBroadcastReceiver extends BroadcastReceiver {
    
        private static final String TAG = SmsBroadcastReceiver.class.getSimpleName();
        public static final String SMS_CONTENT = "sms_content";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "Intent recieved: " + intent.getAction());
    
            Cursor c = context.getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
            c.moveToFirst();
            String smsBody = c.getString(12);
            Toast.makeText(context, "SMS RECEIVED:", Toast.LENGTH_LONG).show();
            Toast.makeText(context, smsBody, Toast.LENGTH_LONG).show();
    
            Intent fireActivityIntent = new Intent(context, SMSDetectorActivity.class);
            fireActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            fireActivityIntent.putExtra(SMS_CONTENT, smsBody);
            context.startActivity(fireActivityIntent);
    
        }
    }

    Also you need specific permissions:

    <uses-permission android:name="android.permission.RECEIVE_SMS">
    <uses-permission android:name="android.permission.READ_SMS">

    Next step is put BroadcastReceiver into AndroidManifest

    <application android:icon="@drawable/ic_launcher" 
        android:label="@string/app_name">
        ..................
        <receiver android:name=".SmsBroadcastReceiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED">
                </action>
            </intent-filter>
        </receiver>
    </application>

    Here you can download source code of this sample Android project

    Download it from github
  • How to fix Android homescreen widget installation. Widget as part of Android application.

    How to fix Android homescreen widget installation. Widget as part of Android application.

    The problem is:
    I have a big Android application. I want to add homescreen widget for this application.

    I’ve followed official tutorial and created widget. It works.

    Then I’ve include all widget’s code into my big application. Also I’ve declared widget in Android Manifest.

    Then app was installed I didn’t see my widget into widget’s list.

    WHY IT DIDN’T APPEARED?

    The answer is very simple!

    My app was installed into SD-card. Moving application to phone was fixed this issue.

    To make widget visible all the time you need put in your AndroidManifest.xml next line:

    android:installLocation="internalOnly"

    It must look like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.hrupin.sample.android"
        android:installLocation="internalOnly" 
        android:versionCode="1"
        android:versionName="1.0" 
        ..........

    Hope it helps

  • How to turn on / turn off WiFi connection programmatically in Android

    How to turn on / turn off WiFi connection programmatically in Android

    Some Android applications can turn on/turn off WiFi on device. How to do same.

    First of all you need specify uses-permission in Android Manifest file

    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

    And now you can enable wifi state via WiFiManager:

    wifiManager.setWifiEnabled(true);

    or disable:

    wifiManager.setWifiEnabled(false);

    Below you can download source code of sample android project

    The source code of main Activity is:

    package com.hrupin.wifiSample;
    
    import android.app.Activity;
    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.net.wifi.WifiManager;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ToggleButton;
    import com.hrupin.wifiSample.R;
    
    public class WifiSwitcherExampleActivity extends Activity implements OnClickListener {
        private static ConnectivityManager connectivityManager;
        private ToggleButton tbWiFi;
        private WifiManager wifi;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            tbWiFi = (ToggleButton) findViewById(R.id.toggleButtonWiFi);
            tbWiFi.setOnClickListener(this);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            initButton();
        }
    
        private void initButton() {
            if (isConnected(this, ConnectivityManager.TYPE_WIFI)) {
                tbWiFi.setChecked(true);
            }
        }
    
        private static boolean isConnected(Context context, int networkType) {
            NetworkInfo networkInfo = null;
            if (connectivityManager != null) {
                networkInfo = connectivityManager.getNetworkInfo(networkType);
            }
            return networkInfo == null ? false : networkInfo.isConnected();
        }
    
        @Override
        public void onClick(View v) {
            if (v.getId() == tbWiFi.getId()) {
                wifi.setWifiEnabled(tbWiFi.isChecked());
            }
        }
    }

    Android Manifest:

    <!--?xml version="1.0" encoding="utf-8"?-->
    <manifest 
        xmlns:android="http://schemas.android.com/apk/res/android" 
        package="com.hrupin.wifiSample" 
        android:versioncode="1" 
        android:versionname="1.0">
    
        <uses-sdk android:minsdkversion="8">
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
        <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
        <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission></uses-permission></uses-sdk>
    
        <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
            <activity android:name=".WifiSwitcherExampleActivity" android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN"/>
                    <category android:name="android.intent.category.LAUNCHER"/>
                </intent-filter>
            </activity>
        </application>
    </manifest>

    Here you can download the source code of sample Android application.

    Download it from github
  • How to deal with Lucida Grande Regular & Lucida Grande Bold font in ActionScript3

    How to deal with Lucida Grande Regular & Lucida Grande Bold font in ActionScript3

    To embed Lucida Grande Regular &/or Lucida Grande Bold font in ActionScript3 you need to do next:

    ....
    ....
    ....
    // declaring fonts
    [Embed(source="fonts/Lucida_Grande_Regular.ttf", fontFamily="Lucida_Grande_Regular", fontWeight="normal", mimeType="application/x-font-truetype", embedAsCFF="false")]
    private var LucidaGrandeRegular:Class;
    [Embed(source="fonts/Lucida_Grande_Bold.ttf", fontFamily="Lucida_Grande_Bold", fontWeight="normal", mimeType="application/x-font-truetype", embedAsCFF="false")]
    private var LucidaGrandeBold:Class;
    ....
    ....
    ....
    ....
    // For Regular Font
    // Create TextFormat with embeded font
    var format:TextFormat = new TextFormat();
    format.size = 17;
    format.font = "Lucida_Grande_Regular";
    format.bold = false;
    format.italic = false;
    format.color = 0xFFFFFF;
    format.align = TabAlignment.CENTER;
    // Use TextFormat
    var text:TextField = new TextField();
    text.embedFonts = true;
    text.defaultTextFormat = format;
    
    ....
    ....
    ....
    
    // For Bold Font
    // Create TextFormat with embeded font
    var format2:TextFormat = new TextFormat();
    format2.size = 17;
    format2.font = "Lucida_Grande_Bold";
    format2.bold = false;
    format2.italic = false;
    format2.color = 0xFFFFFF;
    format2.align = TabAlignment.CENTER;
    // Use TextFormat
    var text2:TextField = new TextField();
    text2.embedFonts = true;
    text2.defaultTextFormat = format2;

    That’s it :).
    Please, write questions in comments.
    Don’t forget share this post 🙂

  • Сannot create the APKBuilder object Debug Certificate expired

    Сannot create the APKBuilder object Debug Certificate expired

    When I run my Android application I catch next error:

    “Сannot create the APKBuilder object Debug Certificate expired on 4/19/12 4:58 PM”

    It means that your debug.keystore sertificate is expired. To fix this just delete it. Exlipse will regenerate a new one.

    You need to delete next file: (in Linux)

    ~/.android/debug.keystore