Sunday, October 13, 2013

Alarm via BoardCast Reciever Android

Hi Guys,

This tutorial might be helpful for leaning about the Alarm with Broadcast Receiver in android.
A Broadcast Receiver is an Android component which allows you to register for system or application events. All registered receivers for an event will be notified by the Android run-time once this event happens. 

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.

If registering a receiver in your Activity.onResume() implementation, you should unregistered it in Activity.onPause(). (You won't receive intents when paused, and this will cut down on unnecessary system overhead). Do not unregistered in Activity.onSaveInstanceState(), because this won't be called if the user moves back in the history stack.  More detail about broadcast receiever Here.

Alarm Manager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes.

There are two way we can registered and unregistered the broadcast receive.
1. Dynamic way
2. Static Way 

Dynamic way:-

You can register a receiver dynamically via the Context.registerReceiver() method. You can also dynamically unregister receiver by using Context.unregisterReceiver() method.

Static Way:-

You can use the PackageManager class to enable or disable receivers registered in your AndroidManifest.xml file.
For Register
ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
For UnRegister
ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

main_activity.xml




MainActivity.java

package com.sunil.br;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

private Button btnstartalarm=null;
private Button btncancelalarm=null;
private Button btnenablebr=null;
private Button btndiablebr=null;
AlarmManager amanager=null;
PendingIntent pi=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnstartalarm = (Button)findViewById(R.id.button_startalarm);
btncancelalarm = (Button)findViewById(R.id.button_cancelalarm);
btnenablebr = (Button)findViewById(R.id.button_enablebr);
btndiablebr = (Button)findViewById(R.id.button_disablebr);

btnstartalarm.setOnClickListener(this);
btndiablebr.setOnClickListener(this);
btncancelalarm.setOnClickListener(this);
btnenablebr.setOnClickListener(this);

}

@Override
public void onClick(View arg0) {

if(arg0==btnstartalarm)
{
amanager=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent= new Intent(this, AlarmManagerBR.class);
pi=PendingIntent.getBroadcast(this, 0, intent, 0);
//After after 2 seconds
amanager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000*4, pi);
Toast.makeText(this, "Start Repating Alarm", Toast.LENGTH_SHORT).show();

}
else if (arg0==btncancelalarm) {

amanager.cancel(pi);
Toast.makeText(this, "Canceled Alarm", Toast.LENGTH_SHORT).show();
}

else if(arg0==btnenablebr){

ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Enable Boradcast Reciever", Toast.LENGTH_SHORT).show();
}
else if (arg0==btndiablebr) {

ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Diable Boradcast Reciever", Toast.LENGTH_SHORT).show();
}
}
}

AlarmManagerBR.java

package com.sunil.br;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmManagerBR extends BroadcastReceiver{

@SuppressLint("SimpleDateFormat")
@Override
public void onReceive(Context arg0, Intent arg1) {

StringBuilder sb=new StringBuilder();
SimpleDateFormat format=new SimpleDateFormat("hh:mm:ss a");
sb.append(format.format(new Date()));
Toast.makeText(arg0, sb, Toast.LENGTH_SHORT).show();
}

}

Manifest.xml


















You can download the source code BoradCastRecieverExample
Cheers Guys!!

Saturday, October 5, 2013

Insert And Retrieve Image into DB

Hi Guys,

In this tutorial we are sharing the code to insert the image into db and retrieve the image from db. I hope this article might be helpful to all learning developer.

SQLite is really a quick and compact android database technology which incorporates SQL syntax to create queries and also handle data.

Android SDK by itself provides the SQLite support which without doubt making the setup as well as utilization process within our applications with no trouble.

Whenever we make use of an Android SQLite Database all of us undoubtedly require the help of SQLiteOpenHelper to handle our data.SQLiteOpenHelper is surely an superb destination to place some initial values right into the android sqlite database when it is built.

For storing the image we are using the blob type. Blob is a Java interface representing the SQL BLOB type.
An SQL BLOB type stores a large array of binary data (bytes) as the value in a column of a database.
The java.sql.Blob interface provides methods for setting and retrieving data in the Blob, for querying Blob data length, and for searching for data within the Blob. More details about Blob Here

But i think in big level storing the image in database is not valuable because database sqlite have limited space so store the image path is valuable.

main_activity.xml








MainActivity.java

package com.sunil.insertimageindb;

import java.io.ByteArrayOutputStream;

import com.sunil.insertimageindb.R;

import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

private ImageView imageview=null;
private Button btninsert=null;
private Button btnretrive=null;
private MyDataBase mdb=null;
private SQLiteDatabase db=null;
private Cursor c=null;
private byte[] img=null;
private static final String DATABASE_NAME = "ImageDb.db";
public static final int DATABASE_VERSION = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btninsert=(Button)findViewById(R.id.button_insert);
btnretrive= (Button)findViewById(R.id.button_retrieve);
imageview= (ImageView)findViewById(R.id.imageView_image);
imageview.setImageResource(0);
btninsert.setOnClickListener(this);
btnretrive.setOnClickListener(this);
mdb=new MyDataBase(getApplicationContext(), DATABASE_NAME,null, DATABASE_VERSION);


Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, bos);
img=bos.toByteArray();
db=mdb.getWritableDatabase();
}
@Override
public void onClick(View arg0) {

if(btninsert==arg0)
{
ContentValues cv=new ContentValues();
cv.put("image", img);
db.insert("tableimage", null, cv);
Toast.makeText(this, "inserted successfully", Toast.LENGTH_SHORT).show();
}
else if(btnretrive==arg0)
{
String[] col={"image"};
c=db.query("tableimage", col, null, null, null, null, null);

if(c!=null){
c.moveToFirst();
do{
img=c.getBlob(c.getColumnIndex("image"));
}while(c.moveToNext());
}
Bitmap b1=BitmapFactory.decodeByteArray(img, 0, img.length);

imageview.setImageBitmap(b1);
Toast.makeText(this, "Retrive successfully", Toast.LENGTH_SHORT).show();
}
}

}

MyDatabase.java

package com.sunil.insertimageindb;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class MyDataBase extends SQLiteOpenHelper{

public MyDataBase(Context context, String dbname, CursorFactory factory, int dbversion) {
super(context, dbname, factory, dbversion);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table tableimage(image blob);");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

Store the image in db looks like that


You can download the source code InsertImageintoDB.
Cheers Guys!!

Wednesday, October 2, 2013

PayPal Android SDK With Multiple In-App Payment

Hi Guys,

I hope this tutorial and article might be helpful for all android developer to make a multiple payment with this new android sdk pay pal in app.
PayPal announced a new Android SDK that tries to make it easier for developers to accept in-app payments on Google�s mobile platform.
As expected, the Android payments solution accepts both PayPal and credit card payments. The company says it is quick and easy to use, and �removes payment friction so developers can focus on creating amazing experiences.�

PayPal�s strategy is to make it as easy as possible for mobile developers to integrate its payments into their work. The pitch is simple: if consumers don�t have to leave your app to pay, and they can do so in more ways than one (click a PayPal button or scan a credit/debit card), they will be more likely to do so.

The new PayPal Android SDK supports Android version 2.2 and up. The new Android payment solution will allow developers to accept payments via PayPal and via credit cards. PayPal believes that giving users the option to pay quickly and easily via their PayPal account or by scanning a credit card will lure more customers into paying developers for their work.

PayPal says that it is also offering security features that will allow developers to �significantly reduce� fraud they encounter with payments. So I think that its really amazing concept for android developer.
More in detail visit the pay pal developer site and git-hub repository Pay Pay Developer.

 
 

main_activity.xml




MainActivity.java

package com.paypal.sunil.paypalandroidsdk;

import java.math.BigDecimal;

import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;

public class MainActivity extends Activity {

// set to PaymentActivity.ENVIRONMENT_LIVE to move real money.
// set to PaymentActivity.ENVIRONMENT_SANDBOX to use your test credentials from https://developer.paypal.com
// set to PaymentActivity.ENVIRONMENT_NO_NETWORK to kick the tires without communicating to PayPal's servers.
private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_NO_NETWORK;

// note that these credentials will differ between live & sandbox environments.
private static final String CONFIG_CLIENT_ID = "credential from developer.paypal.com";
// when testing in sandbox, this is likely the -facilitator email address.
private static final String CONFIG_RECEIVER_EMAIL = "matching paypal email address";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Intent intent = new Intent(this, PayPalService.class);

intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);

startService(intent);
}

public void onBuyPressed(View pressed) {
PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal("1.75"), "USD", "hipster jeans");

Intent intent = new Intent(this, PaymentActivity.class);

intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);

// It's important to repeat the clientId here so that the SDK has it if Android restarts your
// app midway through the payment UI flow.
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, "credential-from-developer.paypal.com");
intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, "your-customer-id-in-your-system");
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);

startActivityForResult(intent, 0);
}

@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i("paymentExample", confirm.toJSONObject().toString(4));

// TODO: send 'confirm' to your server for verification.
// see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
// for more details.

} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("paymentExample", "The user canceled.");
}
else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
Log.i("paymentExample", "An invalid payment was submitted. Please see the docs.");
}
}

@Override
public void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
}

Manifest.xml













































You can download the source code PaypalSDK

 

Copyright @ 2013 Android Developers Tipss.