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.