Friday, September 17, 2010

Adding Voice Search to your Android Phones

Looking forward to add voice search in your google phone??
well its easy

Install.. thats it..
furthermore.. you will be able to find google voice command for 2.2 but it seems they have pulled up the voice search app from the android market..

for installation you need to allow unknown sources in settings -> application -> allow unknown sources

Wednesday, September 15, 2010

Reading data from internet and writing to a file - Andorid

many a times we need to download a data from internet and save on our mobile... well theres an easy example for the same...
In this particular example, i have downloaded a pdf file from internet and saved in my data directory..

package abhi.pdf.downloader;

/*
Copyright [2010] [Abhinava Srivastava]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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

public class PDFDownload extends Activity {

private static final String PDF_OUTPUT_FILENAME = "testFile.pdf";
private final String SAMPLE_URL = "http://java.sun.com/docs/books/jls/download/langspec-3.0.pdf";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
URL url = new URL(SAMPLE_URL);
HttpURLConnection httpConnection = (HttpURLConnection) url
.openConnection();
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
FileOutputStream fos = openFileOutput(PDF_OUTPUT_FILENAME,
MODE_WORLD_WRITEABLE);
// Writing to file
byte buf[] = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0){
fos.write(buf, 0, len);
fos.flush();
}
fos.close();
inputStream.close();

fos.flush();
fos.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

Using Twitter with OAuth On Andorid

Hi There..
many of my friends have been looking to find a way via which they can create applications which have twitter functionality..
well m posting here a small snippet.. this snippet will be helpful for you to understand how can we make twitter work in our application..

Libs we will be using: Twitter4J


package abhi.twitter;

/*
Copyright [2010] [Abhinava Srivastava]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import twitter4j.Twitter;
import twitter4j.http.AccessToken;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class OAuthHelp {

private static final String APPLICATION_PREFERENCES = "tweet_preferences";
private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SEKRET_KEY = "auth_secret_key";
private SharedPreferences preferences;
private AccessToken accessToken;
private String consumerSecretKey;
private String consumerKey;

/**
* OAuthHelp class constructor loads the consumer keys
*
* @param context
*/
public OAuthHelp(Context context) {
preferences = context.getSharedPreferences(APPLICATION_PREFERENCES,
Context.MODE_PRIVATE);
loadConsumerKeys();
accessToken = loadAccessToken();
}

/**
* Depricated method has been used
*
* @param twitter
*/
@SuppressWarnings("deprecation")
public void configureOAuth(Twitter twitter) {
twitter.setOAuthConsumer(consumerKey, consumerSecretKey);
twitter.setOAuthAccessToken(accessToken);
}

/**
* true is accesstoken available false other wise
*
* @return boolean
*
*/
public boolean hasAccessToken() {
return null != accessToken;
}

/**
* Stores access token in preferences
*
* @param accessToken
*/
public void storeAccessToken(AccessToken accessToken) {
Editor editor = preferences.edit();
editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
editor.putString(TWEET_AUTH_SEKRET_KEY, accessToken.getTokenSecret());
editor.commit();
this.accessToken = accessToken;
}

/**
* Loads acess token from SharedPreferences
* @return
*/
private AccessToken loadAccessToken() {
String token = preferences.getString(TWEET_AUTH_KEY, null);
String tokenSecret = preferences.getString(TWEET_AUTH_SEKRET_KEY, null);
if (null != token && null != tokenSecret) {
return new AccessToken(token, tokenSecret);
} else {
return null;
}
}

/**
* Loads default consumer keys
*/
private void loadConsumerKeys() {
consumerKey = "tkU0PAt5vtvY169JO47Duw";
consumerSecretKey = "nYEBvt86WpyXwD84HoePW6q0gFzi4rXhhrEsZghCzlI";
}
}

then just make a simple linking via Calling Activity..


package abhi.twitter;

/*
Copyright [2010] [Abhinava Srivastava]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
* @author abhinava_srivastava
*/

public class TwitterApp extends Activity {

/**
* Twitter instance object
*/
private Twitter twitterConnection = null;
private OAuthHelp oHelper = null;
private RequestToken requestToken = null;
private AccessToken accessToken = null;
private WebView webView = null;
private Context context;
private Handler handleEvent = null;

private static final String CONSUMER_KEY = "tkU0PAt5vtvY169JO47Duw";
private static final String CONSUMER_SECRET = "nYEBvt86WpyXwD84HoePW6q0gFzi4rXhhrEsZghCzlI";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handleEvent = new Handler();
twitterConnection = new TwitterFactory().getInstance();
context = this;
oHelper = new OAuthHelp(this);
}

/**
* Connects to twittter
* @param v
*/
public void getTwitter(View v) {
handleEvent.post(new Runnable() {
@Override
public void run() {
if (oHelper.hasAccessToken()) {
oHelper.configureOAuth(twitterConnection);
try {
twitterConnection.updateStatus("Hii!!!!");
} catch (TwitterException e) {
Log.d("TWEET", "Error Updating status " + e.getMessage());
e.printStackTrace();
}
} else {
try {
twitterConnection.setOAuthConsumer(CONSUMER_KEY,
CONSUMER_SECRET);
requestToken = twitterConnection
.getOAuthRequestToken("");
webViewDialog(requestToken.getAuthorizationURL(), 0);
} catch (TwitterException e) {
e.printStackTrace();
}
}
}
});
}

/**
* Shows Dialog for authentications
*
* @param authorizationURL
* @param type
*/
private void webViewDialog(final String authorizationURL, final int type) {
LinearLayout container = new LinearLayout(this);
container.setMinimumWidth(200);
container.setMinimumHeight(320);
webView = new WebView(this);
webView.setMinimumWidth(200);
webView.setMinimumHeight(380);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(authorizationURL);
container.addView(webView);
Builder webDialog = new AlertDialog.Builder(this);
webDialog.setView(container).setTitle("Web Settings")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
if (type == 0) {
twitterPinCodeDialog();
dialog.dismiss();
}
// dialog.dismiss();
}
}).show();
}

/**
* Pin code dialog Requests the user to enter pin shown on twitter
*/
public void twitterPinCodeDialog() {
LinearLayout pinHolder = new LinearLayout(this);
pinHolder.setGravity(Gravity.CENTER);
final EditText editPinCode = new EditText(this);
editPinCode.setGravity(Gravity.CENTER);
editPinCode.setHint("Pin Code");
editPinCode.setWidth(200);
pinHolder.addView(editPinCode);

Builder pinBuilder = new AlertDialog.Builder(this);
pinBuilder.setView(pinHolder).setTitle("Twitter Pin Code Entry")
.setMessage(
"Please enter displayed twitter code into the field")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
if (editPinCode.getText().toString() != null
&& !editPinCode.getText().toString().equals("")) {
try {
accessToken = twitterConnection
.getOAuthAccessToken(requestToken,
editPinCode.getText()
.toString());
oHelper.storeAccessToken(accessToken);
Log.i("Access Token:", accessToken.getToken());
Log.i("Access Secret:", accessToken
.getTokenSecret());
twitterConnection
.updateStatus("Tweeted Successfully - Abhinava Srivastava");
} catch (TwitterException te) {
if (401 == te.getStatusCode()) {
System.out
.println("Unable to get the access token.");
} else {
te.printStackTrace();
}
}
} else {
Toast.makeText(context, "Pin code is required",
Toast.LENGTH_SHORT).show();
dialog.dismiss();
twitterPinCodeDialog();
}

}
}).setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
Toast
.makeText(
context,
"To share your news please complete login next time",
Toast.LENGTH_LONG).show();
dialog.dismiss();
}
}).show();
}
}

Do not forget to add permission of INTERNET..
@nJoy!