Pages

Wednesday 30 January 2013

Android - Make ImageView's transparent area not clickable


ImageView :
ImageView imgView= (ImageView) findViewById(R.id.color_blue);
imgView.setDrawingCacheEnabled(true);
imgView.setOnTouchListener(changeColorListener); 


OnTouchListener:

private final OnTouchListener changeColorListener = new OnTouchListener() {

  @Override
  public boolean onTouch(final View v, MotionEvent event) {

   Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
   int color = 0;
   try {
    color = bmp.getPixel((int) event.getX(), (int) event.getY());
   } catch (Exception e) {
    // e.printStackTrace();
   }
   if (color == Color.TRANSPARENT)
    return false;
   else {

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
     //do something here
     break;
    case MotionEvent.ACTION_OUTSIDE:
     break;
    case MotionEvent.ACTION_CANCEL:
     break;
    case MotionEvent.ACTION_MOVE:
     break;
    case MotionEvent.ACTION_SCROLL:
     break;
    case MotionEvent.ACTION_UP:
     //do something here
     break;
    default:
     break;
    }
    return true;

   }
  }
 };

Friday 25 January 2013

Android rate your app functionality

use below code to launch rating page on google play.


mContext.startActivity(new Intent(
                                        Intent.ACTION_VIEW, Uri
                                                .parse("market://details?id="
                                                        + APP_PACKAGE_NAME)));

Thursday 24 January 2013

android twitter login implementation

below is code to login twitter.

requirement:
lib need to use : using twitter 4j 
make twitter app at dev consolve of twitter

 private void parseUrl(String url) {
  try {
   if (url == null)
    return;
   if (url.startsWith(General.TWITTER_CALLBACK_URL)) {
    url += "&";

    String oauth_verifier = com.qtm.sign2learn.utils.Util.extractPattern(url,
      "oauth_verifier=(.*?)&");

    AccessToken accessToken = twitter.getOAuthAccessToken(
      requestToken, oauth_verifier);

    twitter.setOAuthAccessToken(accessToken);

    User user = twitter.verifyCredentials();

    String name = user.getName();

    String miniImage = user.getMiniProfileImageURL();
    String bigImage = user.getBiggerProfileImageURL();

    String fbUid = String.valueOf(user.getId());

    Editor edit = prefs.edit();
    edit.putString(General.pref_KEY_OAUTH_TOKEN,
      accessToken.getToken());
    edit.putString(General.pref_KEY_OAUTH_SECRET,
      accessToken.getTokenSecret());
    edit.putString(General.pref_TWITTER_ACCESS_TOKEN,
      accessToken.getToken());
//    edit.putString(General.pref_fb_uid, fbUid);
//    edit.putInt(General.pref_acctype, 2);
    prefs.getBoolean(General.pref_KEY_TWITTER_LOGIN, true);
    edit.commit();
    
    if (progressDialog != null && progressDialog.isShowing()) {
     progressDialog.dismiss();
    }
    loginDialog.dismiss();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 private class TwitterWebViewClient extends WebViewClient {
  @Override
  public void onPageStarted(WebView view, String url, Bitmap favicon) {
   super.onPageStarted(view, url, favicon);
   parseUrl(url);

   progressDialog.show();

  }

  @Override
  public void onPageFinished(WebView view, String url) {
   super.onPageFinished(view, url);
   progressDialog.dismiss();
  }
 }

 public void loginToTwitter(View v) {

  TwitterFactory factory = new TwitterFactory();

  twitter = factory.getInstance();
  twitter.setOAuthConsumer(General.TWITTER_CONSUMER_KEY,
    General.TWITTER_CONSUMER_SECRET);
  try {
   requestToken = twitter
     .getOAuthRequestToken(General.TWITTER_CALLBACK_URL);

   loginDialog = new Dialog(this,
     android.R.style.Theme_Translucent_NoTitleBar);

   loginDialog.setContentView(R.layout.webview_popup);

   Button btnClose = (Button) loginDialog.findViewById(R.id.btnClose);

   btnClose.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
     // TODO Auto-generated method stub
     loginDialog.dismiss();
    }
   });

   WebView webview = (WebView) loginDialog
     .findViewById(R.id.webViewVKLogin);
   webview.getSettings().setJavaScriptEnabled(true);
   webview.clearCache(true);

   webview.setWebViewClient(new TwitterWebViewClient());

   // otherwise CookieManager will fall with
   // java.lang.IllegalStateException:
   // CookieSyncManager::createInstance()
   // needs to be called before CookieSyncManager::getInstance()
   CookieSyncManager.createInstance(this);

   CookieManager cookieManager = CookieManager.getInstance();
   cookieManager.removeAllCookie();

   webview.loadUrl(requestToken.getAuthenticationURL());

   loginDialog.show();

   // this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
   // .parse(requestToken.getAuthenticationURL())));
  } catch (TwitterException e) {
   e.printStackTrace();
  }

 }

In general.java put below variables
 // Twitter oauth urls and details
 public static final String TWITTER_CALLBACK_URL = "url here";
 public static final String TWITTER_CONSUMER_KEY = "key here";
 public static final String TWITTER_CONSUMER_SECRET = "secreat here";

 public static final String URL_TWITTER_AUTH = "auth_url";
 public static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
 public static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
 
 public static final String PREFERENCE_NAME = "twitter_oauth";
 public static final String pref_KEY_OAUTH_TOKEN = "sing2learn_oauth_token";
 public static final String pref_KEY_OAUTH_SECRET = "sing2learn_oauth_token_secret";
 public static final String pref_KEY_TWITTER_LOGIN = "sing2learn_isTwitterLogedIn";
 public static final String pref_TWITTER_ACCESS_TOKEN = "sing2learn_twitter_token";
 



android facebook login implementation

use below code for facebook login.

----- FOR NEW SDK-----

https://developers.facebook.com/docs/android/getting-started/facebook-sdk-for-android/

-----FOR OLD SDK------
you need to use facebook sdk. you can download from developer.facebook.com


private void facebookLogin() {

  facebook = new Facebook(General.FB_APPID);// ((GlobalVars)getApplicationContext()).facebook;

  String access_token = prefs.getString(General.PREFS_FB_token, null);
  Long expires = prefs.getLong(General.PREFS_FB_expires, 0);
  Log.d("MyTag", "token:" + access_token);
  if (access_token != null) {
   facebook.setAccessToken(access_token);
  }
  if (expires != 0) {
   facebook.setAccessExpires(expires);
  }
  /*
   * Only call authorize if the access_token has expired.
   */

  if (!facebook.isSessionValid()) {
   final Editor edit = prefs.edit();
   Log.d("MyTag", "In Authorize");
   facebook.authorize(this,
     new String[] { "publish_stream", "email" },
      new DialogListener() {
      public void onComplete(Bundle values) {
       Log.d("fb login complete",
         "fb login complete");
       Log.d("MyTag",
         "face token: " + facebook.getAccessToken());
       edit.putString(General.PREFS_FB_token,
         facebook.getAccessToken());
       
       edit.putLong(General.PREFS_FB_expires,
         facebook.getAccessExpires());
       edit.commit();
       Toast.makeText(SettingsActivity.this, "login success", Toast.LENGTH_LONG).show();
      }

      public void onFacebookError(FacebookError e) {
       Toast.makeText(getApplicationContext(),
         "onFacebookError", Toast.LENGTH_SHORT)
         .show();
      }

      public void onError(DialogError e) {
       Toast.makeText(getApplicationContext(), "onError",
         Toast.LENGTH_SHORT).show();
      }

      public void onCancel() {

      }
     });
  } else {
   Toast.makeText(this, "login success", Toast.LENGTH_LONG).show();
  }
 }

android play audio/video intent

Audio play intent


Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + filePath),
"audio/*");
startActivity(intent);

video play intent


Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + filePath),
"video/*");
startActivity(intent);

Android choose audio/video or open image using intent

user following code to play audio and video using intent.

Image

Intent intent = new Intent();

intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivity(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);



Aduio


Intent intent = new Intent();

intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivity(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);


Video

Intent intent = new Intent();

intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivity(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);


Friday 11 January 2013

GOOGLE ANDROID C2DM TUTORIAL (ANDROID PUSH NOTIFICATIONS)


Overview of the manifest changes:

Permission to receive C2DM messages
Access to the internet
Restrict access to your C2DM messages so no other app can see them
Declare a Receiver, that we’ll create later, that will let us receive the C2DM events
Make sure that the minSdkVersion is set so that only 2.2 and higher can access your app

<manifest package="com.example.myapp" ...>

   <!-- Only this application can receive the messages and registration result -->
   <permission android:name="com.example.myapp.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
   <uses-permission android:name="com.example.myapp.permission.C2D_MESSAGE" />

   <!-- This app has permission to register and receive message -->
   <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

   <!-- Send the registration id to the server -->
   <uses-permission android:name="android.permission.INTERNET" />

   <application...>
      <!-- Only C2DM servers can send messages for the app. If permission is not set -
any other app can generate it -->
      <receiver android:name=".MyC2dmReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
          <!-- Receive the actual message -->
          <intent-filter>
              <action android:name="com.google.android.c2dm.intent.RECEIVE" />
              <category android:name="com.example.myapp" />
          </intent-filter>
          <!-- Receive the registration id -->
          <intent-filter>
              <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
              <category android:name="com.example.myapp" />
          </intent-filter>
      </receiver>
      ...
   </application>
   ...
</manifest>


----------------------------------------------


Send the Registration call

Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");

registrationIntent.putExtra("app", PendingIntent.getBroadcast(context, 0, new Intent(), 0));

registrationIntent.putExtra("sender", "test@gmail.com"); // google email id for registration

context.startService(registrationIntent);


--------------------------------------------------

receiver for registration and receiving messagess


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.util.Log;

import com.rain.skullcandy.R;
import com.rain.skullcandy.activities.FavoriteLocations;
import com.rain.skullcandy.model.SkullCandyModel;

public class MyC2dmReceiver extends BroadcastReceiver {
private static String KEY = "c2dmPref";
private static String REGISTRATION_KEY = "registrationKey";

private Context context;
@Override
public void onReceive(Context context, Intent intent) {
   this.context = context;
if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
       handleRegistration(context, intent);
   } else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
       handleMessage(context, intent);
   }
}

private void handleRegistration(Context context, Intent intent) {
   String registration = intent.getStringExtra("registration_id");
   if (intent.getStringExtra("error") != null) {
       // Registration failed, should try again later.
   Log.d("c2dm", "registration failed");
   String error = intent.getStringExtra("error");
   if(error == "SERVICE_NOT_AVAILABLE"){
   Log.d("c2dm", "SERVICE_NOT_AVAILABLE");
   }else if(error == "ACCOUNT_MISSING"){
   Log.d("c2dm", "ACCOUNT_MISSING");
   }else if(error == "AUTHENTICATION_FAILED"){
   Log.d("c2dm", "AUTHENTICATION_FAILED");
   }else if(error == "TOO_MANY_REGISTRATIONS"){
   Log.d("c2dm", "TOO_MANY_REGISTRATIONS");
   }else if(error == "INVALID_SENDER"){
   Log.d("c2dm", "INVALID_SENDER");
   }else if(error == "PHONE_REGISTRATION_ERROR"){
   Log.d("c2dm", "PHONE_REGISTRATION_ERROR");
   }
   } else if (intent.getStringExtra("unregistered") != null) {
       // unregistration done, new messages from the authorized sender will be rejected
   Log.d("c2dm", "unregistered");

   } else if (registration != null) {
   Log.d("c2dm", registration);
   Editor editor =
                context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
            editor.putString(REGISTRATION_KEY, registration);
    editor.commit();
      // Send the registration ID to the 3rd party site that is sending the messages.
      // This should be done in a separate thread.
      // When done, remember that all registration is done.
   }
}

private void handleMessage(Context context, Intent intent)
{
//Do whatever you want with the message
}
}


Play YouTube video in WebView without launching new Intent


EDIT : Now you can use YouTube Android Player API to play YouTube video in app.


The API offers these benefits :
  • High-quality video playback supported on Android 2.2 (Froyo) or newer
  • Easy integration with your Android application (no WebView required)
  • Fullscreen and orientation change support
  • Integration with the Android YouTube app using a standard set of YouTube Intents
  • And more ..
For further information on this, please Click Here or Here

ORIGINAL POST


Here's the code to play YouTube videos in WebView using video url.
Video plays in appliction itself, not launching new Intent.

XML code file:

activity_video.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".VideoActivity" >

    <Button
        android:id="@+id/btnPlay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|top"
        android:layout_margin="5dp" />

    <WebView
        android:id="@+id/videoView"
        android:layout_width="fill_parent"
        android:layout_height="match_parent" />

</LinearLayout>


Java Code File:

VideoActivity.java

public class VideoActivity extends Activity {
public static final int USER_MOBILE = 0;
public static final int USER_DESKTOP = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
final WebView video = (WebView) findViewById(R.id.videoView);
Button btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setText("Play Video");

btnPlay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
video.getSettings().setJavaScriptEnabled(true);
video.getSettings().setPluginState(WebSettings.PluginState.ON);
video.getSettings().setUserAgent(USER_MOBILE);
video.setWebChromeClient(new WebChromeClient() {
});

//youtube video url
////http://www.youtube.com/watch?v=WM5HccvYYQg

 final String mimeType = "text/html";
final String encoding = "UTF-8";
String html = getHTML("WM5HccvYYQg");
video.loadDataWithBaseURL("", html, mimeType, encoding, "");
}
});
}


public String getHTML(String videoId) {

String html =
"<iframe class=\"youtube-player\" "
+ "style=\"border: 0; width: 100%; height: 95%;"
+ "padding:0px; margin:0px\" "
+ "id=\"ytplayer\" type=\"text/html\" "
+ "src=\"http://www.youtube.com/embed/" + videoId
+ "?fs=0\" frameborder=\"0\" " + "allowfullscreen autobuffer "
+ "controls onclick=\"this.play()\">\n" + "</iframe>\n";

/**
 * <iframe id="ytplayer" type="text/html" width="640" height="360"
 * src="https://www.youtube.com/embed/WM5HccvYYQg" frameborder="0"
 * allowfullscreen>
 **/

return html;
}

}
Manifest.xml file:
Add the line android:hardwareAccelerated="true" in <appliction> tag

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...>
<application
        android:hardwareAccelerated="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
...
...
</application>
</manifest>

android video recording


Here is complete example of how to record video in android device.
(Note: test project in real device not in emulator)

1.  Video View Activity
  
    
import java.io.File;
import java.io.IOException;
import java.util.Date;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.Menu;
import android.view.SurfaceView;
import android.widget.Toast;

public class VideoViewActivity extends Activity implements Callback {

    @Override
    protected void onDestroy() {
        stopRecording();
        super.onDestroy();
    }

    private SurfaceHolder surfaceHolder;
    private SurfaceView surfaceView;
    public MediaRecorder mrec = new MediaRecorder();   
    private Camera mCamera;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
        mCamera = Camera.open();
      
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
              
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {

        menu.add(0, 0, 0, "Start");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if(item.getTitle().equals("Start"))
        {
            try {
              
                startRecording();
                item.setTitle("Stop");

            } catch (Exception e) {

                String message = e.getMessage();
                Log.i(null, "Problem " + message);
                mrec.release();
            }

        }
        else if(item.getTitle().equals("Stop"))
        {
            mrec.stop();
            mrec.release();
            mrec = null;
            item.setTitle("Start");
        }

        return super.onOptionsItemSelected(item);
    }

    protected void startRecording() throws IOException
    {
        if(mCamera==null)
            mCamera = Camera.open();
      
         String filename;
         String path;
      
         path= Environment.getExternalStorageDirectory().getAbsolutePath().toString();
        
         Date date=new Date();
         filename="/rec"+date.toString().replace(" ", "_").replace(":", "_")+".mp4";
        
         //create empty file it must use
         File file=new File(path,filename);
        
        mrec = new MediaRecorder();

        mCamera.lock();
        mCamera.unlock();

        // Please maintain sequence of following code.

        // If you change sequence it will not work.
        mrec.setCamera(mCamera);   
        mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mrec.setAudioSource(MediaRecorder.AudioSource.MIC);   
        mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
        mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mrec.setPreviewDisplay(surfaceHolder.getSurface());
        mrec.setOutputFile(path+filename);
        mrec.prepare();
        mrec.start();

      
    }

    protected void stopRecording() {

        if(mrec!=null)
        {
            mrec.stop();
            mrec.release();
            mCamera.release();
            mCamera.lock();
        }
    }

    private void releaseMediaRecorder() {

        if (mrec != null) {
            mrec.reset(); // clear recorder configuration
            mrec.release(); // release the recorder object
        }
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.release(); // release the camera for other applications
            mCamera = null;
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {     

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {     

        if (mCamera != null) {
            Parameters params = mCamera.getParameters();
            mCamera.setParameters(params);
            Log.i("Surface", "Created");
        }
        else {
            Toast.makeText(getApplicationContext(), "Camera not available!",
                    Toast.LENGTH_LONG).show();

            finish();
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mCamera.stopPreview();
        mCamera.release();     

    }
}



2. main.xml file

    
         <SurfaceView android:id="@+id/surface_camera"     xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:layout_weight="1"
        >
    </SurfaceView>





3.  Get following permission in AndroidManifest.xml

      <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


android unicode text to readable text

you need to use appropriate unicode font to do that.
for example if you want to print hindi then you have to use any hindi font file

suppose hindi font file is "hindi.ttf"
then to print hindi unicode into textview you have to set hindi font like following

txtLyricsEnglish = (TextView) findViewById(R.id.txtLyricsEnglish);
Typeface font = Typeface.createFromAsset(getAssets(),
    "hindi.ttf");
txtLyricsEnglish.setTypeface(font);


Wednesday 9 January 2013

how to generate facebook key hashes


Android KEY HASH  for Facebook :

Download openSSl from :
http://code.google.com/p/openssl-for-windows/downloads/detail?name=openssl-0.9.8k_WIN32.zip

Extract it. create a folder- OpenSSL in C:/ and copy the extracted code here.

Detect debug.keystore file path.

Detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Intel\.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary | "C:\OpenSSL\bin\openssl" base64

so facebook "key hash" for this pc is like JdiLgmuFZfHkh79Ejcy2OKGlzkQ=

Tuesday 8 January 2013

android project export "Conversion to Dalvik format failed with error 1" on external JAR

Go to Project » Properties » Java Build Path » Libraries and remove all except the "Android X.Y" (in my case Android 1.5). click OK. Go to Project » Clean » Clean projects selected below » select your project and click OK. That should work.

It is also possible that you have a JAR file located somewhere in your project folders (I had copied the Admob JAR file into my src folder) and THEN added it as a Java Path Library. It does not show up under the Package Explorer, so you don't notice it, but it does get counted twice, causing the dreaded Dalvik error 1.

Another possible reason could be package name conflicts. Suppose you have a package com.abc.xyz and a class named A.java inside this package, and another library project (which is added to the dependency of this project) which contains the same com.abc.xyz.A.java, then you will be getting the exact same error. This means, you have multiple references to the same file A.java and can't properly build it.

Tuesday 1 January 2013

in java is HashMap() sorted on keys by default?

Use LinkedHashMap if you want to store your data in the order in which keys are inserted into the Map. 
HashMap doesn't guarantee any order.

android listview list item with checkbox not able to click list item

please set check box 's android:focusable="false"
or if other element like edit text  etc