Friday, December 31, 2010

Showing Notification in Android




When we talk about notification we need to consider 3 major aspects.

1. What is Notification
2. Why Notification
3. How to create Notification

What is Notification:
Notification are the messages which are produced at top in the status bar in your android phones. Its a service which is used to show data of your application to the users even when the application is not running on the screen.


Why Notification
Something similar to you SMS Application. As soon as you recieve a SMS you recieve a notification at the top of your screen. The same results can be obtained by your application when using Notification.
Hence, multiple number of times when you are doing some background processes using your Services (e.g. Server request to check for new data on server) and you want to tell user that you have obtained new data and he should launch your application, at this point you will show them Notification message stating that new data has arrived.


How To Use
/**
* 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.
*/

package abhi.blog.notification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RemoteViews;

/**
* Notification Example class
*
* @author Abhinava Srivastava
*
*/
public class NotificationCaller extends Activity {

// PASSED AS PAREMETER TO NOTIFICATION
private final int NOTIFICATION_ID = 0;


// NotificationManager Reference Holder
private NotificationManager mNotificationManager = null;

// NOtification Reference Holder
private Notification mNotification = null;

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

/**
* Need to use NotificationManager Instance of NotificationManger is
* available in our SystemServices which is available in our context.
*/
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

/**
* To clear any existing NOtification with same ID
*/
mNotificationManager.cancel(NOTIFICATION_ID);
}

/**
* Function to handle click event generated by our button
*
* @param v
*/
public void launchNotification(View v) {



/**
* After we have obtained instance of notification manager we need to
* create the notification that we need to show The Constructor of
* Notification takes in 3 Parameters 1. Resource id of icon you want to
* show. 2. Text that should be shown 3. When do you wish to shoe this
* Notification
*/
mNotification = new Notification(R.drawable.icon,
"abhinavasblog.blogspot.com", System.currentTimeMillis());

/**
* Need to setup the view that you need show when user expands his/her
* Status bar.
*/
mNotification.contentView = new RemoteViews("abhi.blog.notification",
R.layout.special_notification);

/**
* Setting up the PendingIntent (Pending Intent is a special kind of
* intent which can be invoked at any specific event) Here we launch our
* application again as soon as we click on the Notification
*/
mNotification.contentIntent = PendingIntent.getActivity(
NotificationCaller.this, 0, new Intent(NotificationCaller.this,
NotificationCaller.class),
PendingIntent.FLAG_CANCEL_CURRENT);

/**
* Finally, we set the created Notification in NotificationManagers
* instance.
*/
mNotificationManager.notify(NOTIFICATION_ID, mNotification);

}
}


main.xml


android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>




special_notification.xml


xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:orientation="vertical" android:layout_height="wrap_content">












Wish you all a Very Happy New Year

Monday, December 13, 2010

Andorid 2.3 Gingerbread

Hey there,
well it has been quite a news for everyone that Android has launched its new 2.3 code name Gingerbread.
had been looking around the updates we gonna get with this new OS update, thought about sharing some info's about the same...

There had been addition of couple of new kool features... like

SIP-based VoIP and NFC(Near Field Communicator)

Whats SIP-based VoIP?

SIP (Session Initiated Protocol) is a protocol which had been defined by IETF (Internet Engineering Task Force).
Sip is majorly used to controll multimedia communication such as Voice or Video communication over IP also know as VoIP (Voice Over Internet Protocol).
Till 2.2 if you wish to develop application based on VoIP you had to implement SIP and VoIP stack on your own. Hence as we move with 2.3 the advantages of pre-implementations will always prove beneficial to the developers also to the users who are looking for some alternative in same domain.
With Sip based VoIP install in your new device you can directly make VoIP calls from your default calling application in Gingerbread.

NFC (Near Field Communications)

NFC is a short range high frequency wireless data communication technology, which enables user to communicate with any NDEF enabled devices, these devices can be posters, car locks or anything that you can imagine, to work with NFC you need to place your device in proximity of 10 cms. ie around 4 inches. With the addition of this new for of communication people now can extract information with more and more different kind of places/devices.


Well that was a quick update about what i came accross, yes there are LOT more in new Andorid,
I will be posting updates as soon as i find some time! :)

Hope you got to learn something new today!

@nJoy!
Abhinava




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!