Thursday 26 December 2013

Building Web Apps in WebView

If you want to deliver a web application (or just a web page) as a part of a client application, you can do it using WebView. The WebView class is an extension of Android's View class that allows you to display web pages as a part of your activity layout.It does not include any features of a fully developed web browser, such as navigation controls or an address bar. All that WebView does, by default, is show a web page.

Create your layout: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<WebView 
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

within your Activity: MainActivity.java

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {
    WebView webView;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        webView = (WebView)findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);

// Handling page navigation
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("http://ashfaquedl.blogspot.in/");
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setBuiltInZoomControls(true);
    }
//  Navigating web page history
    @Override
    public void onBackPressed() {
        if (webView.copyBackForwardList().getCurrentIndex() > 0) {
            webView.goBack();
        }
        else {
            // Your exit alert code, or alternatively line below to finish
            super.onBackPressed(); // finishes activity
        }
    }

}
 Note: And most important thing don't forget to add below uses-permission in AndroidMenifest.xml.

<uses-permission android:name="android.permission.INTERNET"/>
now your app is rocking.
 

Tuesday 19 November 2013

How to clear cache in Android Manually & Programmatically

What the android os does is when you exit an application it actually stores the apps cache on either your phones internal storage or on the sdcard; so what this does, is that when you load the application next time, it immediately loads the stored cache back into your active cache for the purpose of speeding up loading time. So in theory, stored cache is actually a good thing.
However, this is not always the case.
Its only really a beneficial feature for certain applications, like Google maps, where loading all those images normally takes a long time (relatively speaking of course.. its still really fast). An even better example would be your launcher app; your always loading the exact same homescreens everytime. But for other apps it actually is a bad thing and bogs your system down. Why? Because your taking over the fastest available memory on your device with stored data that might not be essential/relevant for what your doing the next time you load the application. A good example would be your web browser. The last time you ran it you were checking the news or watching youtube videos... but now your just doing a google search; you certainly don't need to load the cache from your last session. Get it? 

Clear Cache manually 
< Applications --> Manage Applications --> "My App" --> Clear Cache>> 
Clear cache programmatically

import java.io.File;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

public class HelloWorld extends Activity {

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle *) {
      super.onCreate(*);
      setContentView(R.layout.main);
   }

   @Override
   protected void onStop(){
      super.onStop();
   }

   //Fires after the OnStop() state
   @Override
   protected void onDestroy() {
      super.onDestroy();
      try {
         trimCache(this);
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }

   public static void trimCache(Context context) {
      try {
         File dir = context.getCacheDir();
         if (dir != null && dir.isDirectory()) {
            deleteDir(dir);
         }
      } catch (Exception e) {
         // TODO: handle exception
      }
   }

   public static boolean deleteDir(File dir) {
      if (dir != null && dir.isDirectory()) {
         String[] children = dir.list();
         for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
               return false;
            }
         }
      }

      // The directory is now empty so delete it
      return dir.delete();
   }

}
  
 

Wednesday 13 November 2013

How to save SMS to INBOX in Android Programmatically


There is below code

                ContentValues values = new ContentValues();
                values.put("address", "123456789");
                values.put("body", "foo bar");
                getContentResolver().insert(Uri.parse("content://sms/inbox"), values);

you can save SMS to Sent box also just require to few change.
Replace  ("content://sms/inbox") to ("content://sms/sent").



Below Android Permissions required

    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.WRITE_SMS"/>
How to access Gmail Particular Label content programmatically


              javax.mail.Folder inbox = store.getFolder("SMS");
              inbox.open(Folder.READ_WRITE);
              Message messages[] = inbox.getMessages();
              int count =  messages.length;
              Log.d("SMS count ", ""+count);
              for (Message message : messages){
            // System.out.println(message);
              Log.d("inbox msssgggggg ", "Sub : "+message.getSubject()
                      +" Body :"+message.getContent().toString() +" From
                       :"+message.getFrom());
              }

          Where store is IMAPStore object


Thursday 31 October 2013

how to get / find your device IMEI number programmatically in andorid 

 

TelephonyManager telephonyManager = 
         (TelephonyManager) this.getSystemService(
         Context.TELEPHONY_SERVICE);
String IMEI_Number = telephonyManager.getDeviceId();
Log.d("your device IMEI number -->",IMEI_Number); 
 
  
Requires permission android.permission.READ_PHONE_STATE. 

Dial *#06# to know your IMEI Number or Remove 
your battery and look for IMEI,you will find it.

 

Saturday 12 October 2013

AsyncTask

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

Usage


AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }


Once created, a task is executed very simply:

 new DownloadFilesTask().execute(url1, url2, url3);
 

AsyncTask's generic types


The three types used by an asynchronous task are the following:

  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

 private class MyTask extends AsyncTask<Void, Void, Void> { ... }
 

Monday 30 September 2013

Solutions to Common Android Wi-Fi Problems

Friends of mine who use an Android come over to me usually with problems related to their devices’ Wi-Fi connectivity. Moreover, it’s not a single isolated issue. There are all kinds of them they bring up.

I usually fix their problem after few troubleshoots but today while I was fixing a problem on my device, I realized that it could happen to any one — even to my readers on Blogspot.com. Hence we are going to discuss four of the most common Android Wi-Fi problems and see the probable causes and solutions to them.

 

Android Cannot Scan a Wi-Fi Network

Reason
There may be two reasons as to why your Android cannot scan a network automatically. The first reason may be that the network you are trying to connect to could be Ad-Hoc in nature. As most of the Android phones are not configured to work on Ad-Hoc networks but on access points, they don’t scan them.
The second reason may be that the Wi-Fi network you are trying to connect to might be hidden for security reasons.
Solution
By default, Android does not support Ad-Hoc Wi-Fi network but many developers patch the wpa_supplicant file on Android in order for them to work. If you do a quick Google search you will be able to find if there’s a fix available for your device but the fix can only be performed on a rooted phone. Furthermore, don’t forget to back up your original wpa_supplicant file if at all your phones goes into foreclose or boot loops.
ad network manually
If the problem is with the hidden network, you can try to add the network manually. In Android Wi-Fi settings open menu and tap to add a network manually. You must enter the correct SSID and authentication type and password in order to connect to the network. If both the credentials are correct, the Android phone will be able to connect to the network.

Wi-Fi Keeps Disconnecting Frequently

Reason
The most obvious reason for the problem may be with the Wi-Fi Sleep Policy which disconnects your Wi-Fi every time your Android goes to sleep to save your battery’s juice.
Solution
To manage Wi-Fi Sleep Policy, open Advance Wi-Fi settings on Android and tap the option Keep Wi-Fi on during sleep. Here, check the option Always  to enjoy an uninterrupted connectivity, but you will have to compensate it with your battery life.
advanced settingskeep wifi on
If you are using any third-party app to save your battery, check if it’s controlling your Wi-Fi and other radio services and configure accordingly.

Obtaining IP Address Infinite Loop

Reason
I don’t know the exact reason behind this, but it might be a bug in Android. I have seen many people getting this problem, and it gets kind of annoying when the problem does not gets fixed even after restarting the device.
Solution
First of all, you must restart your Wi-Fi router and see if that helps. Many people say that resetting the phone to factory state works but that’s not an appropriate solution. Wi-Fi Fixer is an amazing Android app that can help you here. The app resets your Wi-Fi system files (same as when you reinstall the Wi-Fi drivers in Windows, or you disable and enable the Wi-Fi adapter) and services and helps you to connect to the network and obtain the IP address.
Wifi fixer
If you know the range of IP address the router is broadcasting, you may configure your Android to use static IP address while connecting to the network.

Can’t Connect to Internet using Wi-Fi

Reasons
There may be several reasons as to why you are not able to connect to the internet even when you are connected to the Wi-Fi. The reasons may be:
  • The router is not broadcasting internet services.
  • The IP address or the gateway is wrong.
  • Problem with the DNS settings.
Solutions
You may use another device to check if the router is actually broadcasting internet. Also you can configure the IP address, the gateway and DNS manually to connect as their might be problems with DHCP.

Conclusion

These are pretty much most of the Android problems one might encounter on his device and the probable solution one can try to fix the problem. I don’t guarantee that you will fix the problem but it’s a good start nonetheless. And most of the solutions should work actually.

Friday 27 September 2013

Access GMail with imap using java mail api

 

I had to search through quite a few web pages for this. So I am putting it here for future reference. My conscience pricks for putting all the code in main method. But I guess this is an exception.  :)

import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
public class InboxReader {
public static void main(String args[]) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>", "password");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message);
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
}



Use the code below to get the available gmail folders for your account
 
Folder[] folder = store.getDefaultFolder().list();

// get the array folders in server
int i=0;
for( i=0;i<folder.length;i++)
System.out.println("Press "+i
 +" to read "+folder[i].getName()+" folder");
int choice=in.nextInt(); 
// getName() method returns the name of folder

Wednesday 25 September 2013

Android Get Application Context

When we are inside an activity, and we need an application context we can use
getApplicationContext() method. But what if we are not inside an activity and we need an application context? Well, I'll explain in this tutorial how  you can get the context of the application outside an Activity.

You have to create a new class called "ApplicationContextProvider"  which will provide the context wherever in the application, code looks like this:


import android.app.Application;
import android.content.Context;
 
 
public class ApplicationContextProvider extends Application {
 
    /**
     * Keeps a reference of the application context
     */
    private static Context sContext;
 
    @Override
    public void onCreate() {
        super.onCreate();
 
        sContext = getApplicationContext();
 
    }
 
    /**
     * Returns the application context
     *
     * @return application context
     */
    public static Context getContext() {
        return sContext;
    }
 
}
 
Now you have to declare this class in the AndroidManifest.xml in the application tag:
 
 
<application android:name=".ApplicationContextProvider"
             android:label="@string/app_name">
  


And that's all. You can get now the application context wherever you need it by simply calling


1
ApplicationContextProvider.getContext();


Tuesday 24 September 2013

Internet connection on pc through mobile Samsung galaxy y

I'll show you how to tether internet from your phone to your computer

 Mobile internet tethering using pre installed application.

 Some phone doesn't have pre-installed tethering application.

To tether internet using your pre installed app.

1- Connect your phone to your computer.

2- In your phone, Open Settings.

3- Select Wireless & Networks.

4- Check USB tethering.

5- The Computer should now be connected to the internet.

I will show you how to tether internet from your phone to your computer. ►Mobile Internet Tethering using pre-installed application. •Some phone doesn`t have pre-installed tethering application. If your phone doesn`t have tethering app proceed to the next tutorial. To tether internet using your pre-installed app: 1. Connect your phone to your computer. 2. In your phone, Open Settings. 3. Select Wireless & Networks. 4. Choose Tethering & Mobile Hotspot. 5. Check USB Tethering. 6. The computer should now be connected to the internet.

Read more: How to connect samsung galaxy y as internet modem to my PC? - How i can connect internet from my galaxy y android to pc. I am unable to connect internet through kies .so please help me :: Ask Me Fast at http://www.askmefast.com/How_to_connect_samsung_galaxy_y_as_internet_modem_to_my_PC-qna1264923.html

 

I will show you how to tether internet from your phone to your computer. ►Mobile Internet Tethering using pre-installed application. •Some phone doesn`t have pre-installed tethering application. If your phone doesn`t have tethering app proceed to the next tutorial. To tether internet using your pre-installed app: 1. Connect your phone to your computer. 2. In your phone, Open Settings. 3. Select Wireless & Networks. 4. Choose Tethering & Mobile Hotspot. 5. Check USB Tethering. 6. The computer should now be connected to the internet.

Read more: How to connect samsung galaxy y as internet modem to my PC? - How i can connect internet from my galaxy y android to pc. I am unable to connect internet through kies .so please help me :: Ask Me Fast at http://www.askmefast.com/How_to_connect_samsung_galaxy_y_as_internet_modem_to_my_PC-qna1264923.html
I will show you how to tether internet from your phone to your computer. ►Mobile Internet Tethering using pre-installed application. •Some phone doesn`t have pre-installed tethering application. If your phone doesn`t have tethering app proceed to the next tutorial. To tether internet using your pre-installed app: 1. Connect your phone to your computer. 2. In your phone, Open Settings. 3. Select Wireless & Networks. 4. Choose Tethering & Mobile Hotspot. 5. Check USB Tethering. 6. The computer should now be connected to the internet.

Read more: How to connect samsung galaxy y as internet modem to my PC? - How i can connect internet from my galaxy y android to pc. I am unable to connect internet through kies .so please help me :: Ask Me Fast at http://www.askmefast.com/How_to_connect_samsung_galaxy_y_as_internet_modem_to_my_PC-qna1264923.ht

Friday 20 September 2013

Using Oauth 2.0 login gmail in android


Below steps require to login gmail using Oauth2.0

1- Select an account from your device using below code

public static AccountManager accountManager;
accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");
 
2- Get a Token from selected account using below code
 
private void onAccountSelected(final Account account) {
    accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, null, this, 
           new AccountManagerCallback<Bundle>() {
        public void run(AccountManagerFuture<Bundle> future) {
            try {
                String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
                useToken(account, token);
            } catch (OperationCanceledException e) {
                onAccessDenied();
            } catch (Exception e) {
                handleException(e);
            }
        }
    }, null);
}
 
3-  now authenticate the token using user account and token you will be able to login.
 
Note:   After sometime token get unauthorized so you need to invalidate your token.

4- for re login you have to invalidate your token using below code

accountManager.invalidateAuthToken("com.google", token);
 
5- After invalidate you have to get a new token using below code
 
String newToken = AccountManager.get(this).getAuthToken(new Account(account, "com.google"),
       AUTH_TOKEN_TYPE, true, null, null).getResult().getString(AccountManager.KEY_AUTHTOKEN);
 
 
Thats all you need to do. Any suggestion will be appreciated. 

 
 

Tuesday 17 September 2013

Debugging in eclipse with real Android phone on ubuntu



First open your device terminal
 
 1)on the top left hand corner in Application ->Accessories->terminal
 2) on terminal window type following commands
 $ sudo su then press enter after that terminal want password which  
   is set by you in  installation or giving at the time of logging.
 
 $<Enter password> password is not shown but it is type 
      internally you can just type whole password 
   $ mkdir ~/.android
   $vi ~/.android/adb_usb.ini
   press ctri+z here
   $ echo "0x0451" > ~/.android/adb_usb.ini
   $cat /root/.android/adb_usb.ini
    $sudo mount -t usbfs none /proc/bus/usb
   $cd path of android sdk tools from home
     like /home/tv-014/Desktop/newandroid/android-sdk-linux/platform-tools
   in my system i have put android-sdk-linux at desktop and in it one 
    platform-tools 
   folder contain the adb.exe file
   so after cd command we have the path from home to platform-tools folder.
    $ ./adb kill-server
    $ ./adb start-server
    $ ./adb devices
 
 
now you got the list of devices attached to your system 

Monday 16 September 2013



Download and Install AndroidSDK in Ubuntu 12.04 (Precise Pangolin) 

Android SDK is a development environment for the Android mobile operating system which allows you to write applications for Android devices or gain elevated privileges on android devices with the help of third party software.
This brief tutorial is going to show you how to download and install it in Ubuntu 12.04 if you haven’t already done so. To install it, you first need to install Java JDK package or use the openJDK Java alternative that comes with Ubuntu.
In this tutorial, I’m going to be using the openJDK version of Java. To install Oracle Java version, then read this post first.
Objectives:
  • Install AndroidSDK in Ubuntu 12.04 (Precise Pangolin)
  • Enjoy!

To get started, press Ctrl – Alt – T on your keyboard to open the terminal. When it opens, run the commands below to install OpenJDK.
sudo apt-get install openjdk-6-jre openjdk-6-jdk icedtea6-plugin

android_precise

Next, download AndroidSDK package by running the commands below. At the time of this writing, the current version was r20. Or click this link to download the .tgz archive file.
wget http://dl.google.com/android/android-sdk_r20-linux.tgz

android_precise_1

After downloading, run the commands below to extract the downloaded file.
tar -xvzf android-sdk_r20-linux.tgz

android_precise_2

After extracting the package, run the command below to change into the tools directory.
cd ~/android-sdk-linux/tools

android_precise_3

Finally, run the commands below to begin the installation.
./android

android_precise_4

Install Android updates if there are any available.

android_precise_5

After updating, run the commands below to include AndroidSDK in your path environment.
gedit ~/.bashrc

Then add these lines at the very top of the file and save it.
export PATH=${PATH}:~/android-sdk-linux/tools



export PATH=${PATH}:~/android-sdk-linux/platform-tools

android_precise_6


Log out and log back in, then type android on the command line to launch the software.
android avd

Build your own phone.

android_precise_7