PayPal.initWithAppID() crashes with NullPointerException - android

FATAL EXCEPTION: Thread-5195
java.lang.NullPointerException: src == null
at java.lang.System.arraycopy(Native Method)
at com.paypal.android.a.g.a(Unknown Source)
at com.paypal.android.a.h.c(Unknown Source)
at com.paypal.android.MEP.PayPal.setLanguage(Unknown Source)
at com.paypal.android.MEP.PayPal.initWithAppID(Unknown Source)
at com.lonfun.pets.UnityPayMenuActivity.initLibrary(UnityPayMenuActivity.java:256)
at com.lonfun.pets.UnityPayMenuActivity.access$2(UnityPayMenuActivity.java:249)
at com.lonfun.pets.UnityPayMenuActivity$2$1.run(UnityPayMenuActivity.java:175)
I just use android to open paypal, everything is ok, but if I call from unity, this is happened!
this is my java code:
package com.paypal.androidpets;
import android.content.Context;
import android.os.Handler;
import com.lonfun.pets.UnityPayMenuActivity;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
public class PaypalTool {
Context context;
PayPal pp;
private static final int server = PayPal.ENV_SANDBOX;
// The ID of your application that you received from PayPal
private static final String appID = "APP-80W284485P519543T";
public PaypalTool(Context context) {
this.context=context;
}
public void initLibrary(final Handler handler)
{
new Thread() {
public void run() {
PayPalActivity._paypal = null;
pp = PayPal.getInstance();
// If the library is already initialized, then we don't need to initialize it again.
if(pp == null) {
// pp = PayPal.initWithAppID(context, "", PayPal.ENV_NONE);
pp = PayPal.initWithAppID(context, appID, server);
pp.setShippingEnabled(false);
}
if (PayPal.getInstance().isLibraryInitialized()) {
handler.sendEmptyMessage(0);
}
else {
handler.sendEmptyMessage(1);
}
}
}.start();
}
}
has anybody solve this problem,,please help me, thank you!
using UnityEngine;
using System.Collections;
public class PayMoneyHandler : MonoBehaviour
{
#if UNITY_ANDROID
static AndroidJavaClass payPluginClass;
static AndroidJavaClass unityPlayer;
static AndroidJavaObject currActivity;
#endif
public static void Pay(string productID)
{
#if UNITY_ANDROID
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("StartActivity0",
"com.peten.tier2",
"EGAHCNJDEJBWBIBWEXIKDEGLJECOAD.Mac",
"Dog",
"AndDogCn",
"http://42.121.94.123/TradeWeb/AlipayTrade.aspx",
"http://58.246.188.238/TradeWeb/PaypalTrade.aspx"
);
#endif
}
}
using UnityEngine;
using System.Collections;
public class TestForPaypal : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnClick(){
Debug.Log("Test For Paypal!");
PayMoneyHandler.Pay("test1");
}
}
public void StartActivity0(final String name,final String PlayerName,final String GameID,final String ZoneID,final String payUrl,final String paypalUrl)
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("Order", "name:"+name+"PlayerName:"+PlayerName+"GameID:"+GameID+"ZoneID:"+ZoneID+"payUrl:"+payUrl+"paypalUrl:"+paypalUrl);
Intent payintent=new Intent(mContext,UnityPayMenuActivity.class);
payintent.putExtra("name",name);
payintent.putExtra("PlayerName",PlayerName);
payintent.putExtra("GameID",GameID);
payintent.putExtra("ZoneID",ZoneID);
payintent.putExtra("payUrl",payUrl);
payintent.putExtra("paypalUrl",paypalUrl);
Unity3DMainActiviy.this.startActivity(payintent);
}
});
}

I think you didnot enter the appID and the server detail.
Below is the working code which i have implement and It works fine for me.
I have implement Pay on button click which extends the runnable
Check_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (_paypalLibraryInit) {
showPayPalButton();
//Toast.makeText(Android_PP_Test1Activity.this, captions[position], Toast.LENGTH_SHORT).show();
}
else {
// Display a progress dialog to the user and start checking for when
// the initialization is completed
Thread initThread = new Thread(initLibraryRunnable);
initThread.start();
_progressDialog = new ProgressDialog(Recharge.this);
_progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
_progressDialog.setMessage("Loading PayPal Payment Library");
_progressDialog.setCancelable(false);
_progressDialog.show();
_progressDialogRunning = true;
Thread newThread = new Thread(checkforPayPalInitRunnable);
newThread.start();
//Toast.makeText(Android_PP_Test1Activity.this, "Picasso Paintings", Toast.LENGTH_SHORT).show();
}
}
});
This button call this runnable method
//This lets us run the initLibrary function
final Runnable initLibraryRunnable = new Runnable() {
public void run() {
initLibrary();
}
};
and this method is responsible to initiate the initLibrary.
/** init method **/
public void initLibrary() {
PayPal pp = PayPal.getInstance();
if (pp == null) {
// This is the main initialization call that takes in your Context,
// the Application ID, and the server you would like to connect to.
pp=PayPal.initWithAppID(this,"APP80W284485P519543T",PayPal.ENV_SANDBOX);
// -- These are required settings.
pp.setLanguage("en_US"); // Sets the language for the library.
// --
// -- These are a few of the optional settings.
// Sets the fees payer. If there are fees for the transaction, this
// person will pay for them. Possible values are FEEPAYER_SENDER,
// FEEPAYER_PRIMARYRECEIVER, FEEPAYER_EACHRECEIVER, and
// FEEPAYER_SECONDARYONLY.
pp.setFeesPayer(PayPal.FEEPAYER_EACHRECEIVER);
// Set to true if the transaction will require shipping.
pp.setShippingEnabled(true);
// Dynamic Amount Calculation allows you to set tax and shipping
// amounts based on the user's shipping address. Shipping must be
// enabled for Dynamic Amount Calculation. This also requires you to
// create a class that implements PaymentAdjuster and Serializable.
pp.setDynamicAmountCalculationEnabled(false);
// --
}
}
Hope It helps...

The problem is when unity generates the apk file. I have compared one apk i made miself with PayPal integration only compiling with eclipse and other compiling with Unity.
Lets say the apk i made only with eclipse is called "PayPalOnlyEclipse.apk" and the one made with unity "PayPalWithUnity.apk"; y renamed them to "PayPalOnlyEclipse.zip" and "PayPalWithUnity.zip", then open both with WinRar to compare them.
I found that PayPalOnlyEclipse had one folder that PayPalWithUnity didn't, the folder is "com\paypal\android\utils\data". So I decompressed that folder and then added it to PayPalWithUnity. Then erase the META-INF folder (the signing), then close the "PayPalWithUnity.zip" and rename it like it was before ("PayPalWithUnity.apk").
Then I used the command for signing the apk file:
jarsigner -verbose -sigalg MD5withRSA -digestalg SHA1 -keystore my.keystore PayPalWithUnity.apk user
Finally I used the command for zipalign:
zipalign -v 4 PayPalWithUnity.apk PayPalWithUnity2.apk
that command generates PayPalWithUnity2.apk and that is the apk file you have to install in your phone.
Hope it helps, and sorry for my english.

Check if you have included the PaypalActivity on manifest file. Like this:
<activity android:name="com.paypal.android.MEP.PayPalActivity"
android:configChanges="keyboardHidden|orientation" />
If you have it and it doesnt work yet, include the library on the build path (Properties>>Java Buid Path>>Libraries>>Add JARs) and add it on the "order and export" tab (Properties>>Java Buid Path>>Order and Export).

Related

Unity app calling jar only once on the first android build

Looking at my debug message in Terminal using $ adb logcat -s "app" and $ adb logcat -s Unity, I have noticed that my JAR file is only consulted once when I first build my app to Android (.APK) but every time afterward that I just run my app, the plug-in JAR file is not consulted. Why is that?
public class MyClass
{
public static void MyMethod()
{
Log.i("app", "MyMethod entered");
if (blah)
{
Log.d("app", "If entered");
}
else
{
Log.e("app", "Else entered");
}
blah
}
}
Using $ adb logcat -s "app" I see Log.i and Log.d messages, and below in my Unity3D code, I see the Debug.Log message using $ adb logcat -s Unity
public class MyUnityClass : MonoBehaviour
{
public static void MyUnityMethod()
{
#if UNITY_ANDROID
try
{
using ( AndroidJavaObject androidJavaObject = new AndroidJavaObject("com.example.unityplugin.MyClass") )
{
if (androidJavaObject != null)
{
androidJavaObject.CallStatic("MyMethod");
Debug.Log("androidJavaObject != null SUCCESS!");
}
}
}
catch (Exception e)
{
Debug.LogException(e);
}
#endif
}
}
Every time I run my app on the tablet, a script calls MyUnityMethod() which in turn calls MyMethod() of my JAR, but after the first build, I never see those debug messages again...
You have to use AndroidJavaClass instead of AndroidJavaObject. Also, don't create and destroy the Object each time. Don't enclose the code with the using statement. Just declare the variable as a global variable then re-use it.
Java:
public class MyClass
{
public static void MyMethod()
{
Log.i("app", "MyMethod entered");
}
}
C#:
AndroidJavaClass customClass;
void Start()
{
//Replace with your full package name
customClass = new AndroidJavaClass("com.example.unityplugin.MyClass");
//Call function
MyMethod();
}
public void MyMethod()
{
customClass.CallStatic("MyMethod");
}
If you need the MyMethod function to be static then make the customClass variable static too:
C#:
static AndroidJavaClass customClass;
void Start()
{
//Replace with your full package name
customClass = new AndroidJavaClass("com.example.unityplugin.MyClass");
//Call function
MyMethod();
}
public static void MyMethod()
{
customClass.CallStatic("MyMethod");
}

QR code reader to extract data

i have a sales summary print out and has a QR Code ,
i want to develop an app (IOS and android) that reads the QR code , extract all information,do some calculations,and display in specific form , i tried zxing library but it did not extract all information from the receipt.any tip?
You can use google vision API to achieve this. I personally used this and found it great. The below code snippets should help you.
Put this below line in the gradle.
compile 'com.google.android.gms:play-services:9.4.0'
Use BarcodeDetector and CameraSource classes to capture the QR code on real time and decode it.
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes.size() != 0) {
barcodeInfo.post(new Runnable() { // Use the post method of the TextView
public void run() {
barcodeInfo.setText( // Update the TextView
barcodes.valueAt(0).displayValue
);
}
});
}
}
});
Use a SparseArray to fetch the detections and the displayValue of the elements of this sparse array returns the deocded string.
After extracting the string one can do anything, be it displaying the string or make some calculation out of it etc.
This library is the most popular and easiest of reading QR codes in your Android application.
You should also have a look at the Wiki section of this library for learning about how to integrate this library into your Android Application and how to use this library.
This is how you can use this library.
1. Add this library to your project by adding following line into your dependencies inside build.gradle(Module: app) file
compile 'com.github.nisrulz:qreader:2.0.0'
2. Then, after syncing project files, add the SurfaceView element provided by this library into your XML layout file.
<SurfaceView
android:id="#+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
3. Declare the SurfaceView & QREader inside your Activity's Java file & then initialize it inside onCreate() method.
class MainActivity extends AppCompatActivity{
private SurfaceView mySurfaceView;
private QREader qrEader;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup SurfaceView
// -----------------
mySurfaceView = (SurfaceView) findViewById(R.id.camera_view);
// Init QREader
// ------------
qrEader = new QREader.Builder(this, mySurfaceView, new QRDataListener() {
#Override
public void onDetected(final String data) {
Log.d("QREader", "Value : " + data);
text.post(new Runnable() {
#Override
public void run() {
text.setText(data);
}
});
}
}).facing(QREader.BACK_CAM)
.enableAutofocus(true)
.height(mySurfaceView.getHeight())
.width(mySurfaceView.getWidth())
.build();
}
4. Initialize it inside onResume()
#Override
protected void onResume() {
super.onResume();
// Init and Start with SurfaceView
// -------------------------------
qrEader.initAndStart(mySurfaceView);
}
There are many more possibilities you can do with this library, so I recommend you to visit the GitHub repository and check it out. It's worth a shot!

noclassdeferror for inner class MyLicenseCheckerCallback

Im trying to do this tutorial
But keep getting this error:
08-21 14:12:49.599: E/AndroidRuntime(714):
java.lang.NoClassDefFoundError:
com.akiraapps.LicenseCheck$MyLicenseCheckerCallback
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.vending.licensing.AESObfuscator;
import com.google.android.vending.licensing.LicenseChecker;
import com.google.android.vending.licensing.LicenseCheckerCallback;
import com.google.android.vending.licensing.Policy;
import com.google.android.vending.licensing.ServerManagedPolicy;
public class LicenseCheck extends Activity {
private static final String BASE64_PUBLIC_KEY = "no";
private static final byte[] SALT = new byte[] { no};
private TextView mStatusText;
private Button mCheckLicenseButton;
private LicenseCheckerCallback mLicenseCheckerCallback;
private LicenseChecker mChecker;
// A handler on the UI thread.
private Handler mHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);
mStatusText = (TextView) findViewById(R.id.status_text);
mCheckLicenseButton = (Button) findViewById(R.id.check_license_button);
mCheckLicenseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
doCheck();
}
});
mHandler = new Handler();
// Try to use more data here. ANDROID_ID is a single point of attack.
String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
// Library calls this when it's done.
mLicenseCheckerCallback = new MyLicenseCheckerCallback();
// Construct the LicenseChecker with a policy.
mChecker = new LicenseChecker(
this, new ServerManagedPolicy(this,
new AESObfuscator(SALT, getPackageName(), deviceId)),
BASE64_PUBLIC_KEY);
doCheck();
}
protected Dialog onCreateDialog(int id) {
final boolean bRetry = id == 1;
return new AlertDialog.Builder(this)
.setTitle(R.string.unlicensed_dialog_title)
.setMessage(bRetry ? R.string.unlicensed_dialog_retry_body : R.string.unlicensed_dialog_body)
.setPositiveButton(bRetry ? R.string.retry_button : R.string.buy_button, new DialogInterface.OnClickListener() {
boolean mRetry = bRetry;
public void onClick(DialogInterface dialog, int which) {
if ( mRetry ) {
doCheck();
} else {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://market.android.com/details?id=" + getPackageName()));
startActivity(marketIntent);
}
}
})
.setNegativeButton(R.string.quit_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).create();
}
private void doCheck() {
mCheckLicenseButton.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
mStatusText.setText(R.string.checking_license);
mChecker.checkAccess(mLicenseCheckerCallback);
}
private void displayResult(final String result) {
mHandler.post(new Runnable() {
public void run() {
mStatusText.setText(result);
setProgressBarIndeterminateVisibility(false);
mCheckLicenseButton.setEnabled(true);
}
});
}
private void displayDialog(final boolean showRetry) {
mHandler.post(new Runnable() {
public void run() {
setProgressBarIndeterminateVisibility(false);
showDialog(showRetry ? 1 : 0);
mCheckLicenseButton.setEnabled(true);
}
});
}
private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
public void allow(int policyReason) {
System.out.println("Allow");
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Should allow user access.
displayResult(getString(R.string.allow));
}
public void dontAllow(int policyReason) {
System.out.println("dontAllow");
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
displayResult(getString(R.string.dont_allow));
// Should not allow access. In most cases, the app should assume
// the user has access unless it encounters this. If it does,
// the app should inform the user of their unlicensed ways
// and then either shut down the app or limit the user to a
// restricted set of features.
// In this example, we show a dialog that takes the user to Market.
// If the reason for the lack of license is that the service is
// unavailable or there is another problem, we display a
// retry button on the dialog and a different message.
displayDialog(policyReason == Policy.RETRY);
}
public void applicationError(int errorCode) {
System.out.println("applicationError");
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// This is a polite way of saying the developer made a mistake
// while setting up or calling the license checker library.
// Please examine the error code and fix the error.
String result = String.format(getString(R.string.application_error), errorCode);
displayResult(result);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mChecker.onDestroy();
}
}
I follow the tutorial for setting up LVL as a library project and those imports seem to be ok.
Why do I get this error? Why can it not find the inner class? If I right click and say show definition it jumps to the inner class.
I had same problem.
Below steps solved the probelm
take standard library example
coppied the library.jar file from the library project into your libs folder
So this SO Answer is what fixed it
I created a folder called libs and coppied the library.jar file from the library project included in the licensing package downloaded with the manager
What I dont understand is per this answer this should have been done for me
As I am using ADT 20.0.3
Basically it comes down to an example that I downloaded directly from android and got stuck for a few hours trying to figure out what was wrong and this seems like this step should have been in the readme/help docs OR Im doing something wrong.
If you know why this is the answer and how to do it better please answer and Ill change the answer to yours.
I had the exact same exception and none of the above recommendations worked for me.
However I got mine working by ensuring that your LVL project is a library project (right click project -> properties -> android and tick the "Is Libary" checkbo).
To include this in your application project remove any other references to this and apply the changes. Then if not already there navigate to (right click application project --> properties --> android) and in the library section click Add and select your LVL project. Apply Changes. Ok and clean project.
Hope this helps someone.

PayPal Integration with Android

I have seen some related questions but none focusing on the specific problem I have:
I'm using the PayPal MPL Library.
I build my PayPalPayment object, then create the activity for the checkout to occur. That runs fine. My problem is, on the ResultDelegate I need to call a function from my activity, that occurs after the payment and makes some changes (such as storing SharedPreferences, etc.).
So something like this:
public class ResultDelegate implements PayPalResultDelegate, Serializable {
public void onPaymentSucceeded(String payKey, String paymentStatus) {
System.out.println("SUCCESS, You have successfully completed your transaction.");
System.out.println("PayKey: "+payKey);
System.out.println("PayStatus: "+paymentStatus);
callMyCustomAfterPaymentFunction();
}
...
}
Now the thing is, I tried to create a constructor for ResultDelegate that accepts my activity. My existing code is:
//On the activity class
public class MainMenuActivity extends Activity {
public void onCreate(Bundle savedInstanceState)
{
...
Button buy = (Button) findViewByID(R.id.buy_button);
buy.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
new PurchaseTask(activity).execute();
}
}
}
}
public class PurchaseTask extends AsyncTask <String, Void, String> {
protected String doInBackground()
{
...
PayPal pp = PayPal.getInstance();
CheckoutButton cb = pp.getCheckoutButton(...);
cb.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
ResultDelegate delegate = new ResultDelegate(myActivity);
Intent checkout = PayPal.getInstance().checkout(paument, activity, delegate);
activity.StartActivity(checkoutIntent);
}
}
}
}
//On the ResultDelegate class
public class ResultDelegate implements PayPalResultDelegate, Serializable {
private Activity myActivity;
public void onPaymentSucceeded(String payKey, String paymentStatus) {
System.out.println("SUCCESS, You have successfully completed your transaction.");
System.out.println("PayKey: "+payKey);
System.out.println("PayStatus: "+paymentStatus);
myActivity.performAfterPaymentOperations();
}
...
}
So the goal is to call the activity function from the ResultDelegate. Or even simpler, just to be able to store some SharedPreference changes when the ResultDelegate onPaymentSucceeded() fires.
But I get a NotSerializableException mentioning that the my MyActivity field is not Serializable.
So, then I added the transient identifier to my activity field inside the ResultDelegate, but now I get a NullPointerException.
Paypal Mobile Chekout guide
Implementation provided on paypal website is different from yours. They are doing startActivityForResult() to start PaypalActivity. and when in onActivityResult() method they are checking statusCode to check transaction status and act accordingly.
Follow that document for your implementation.
Here in your code, I donot find a point for using AsyncTask. Your ResultDelegate is Serializable where as Activity is not thats why it is throwing NotSerializableException.
Edit:
As you are developing for Google Android platform, then why not to use Google Checkout In-App?
Edit:
This method will be called when your PaypalActivity will finish. That activity will pass resultCode to this onActivityResult method.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
case Activity.RESULT_OK:
// The payment succeeded
String payKey = data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
// Tell the user their payment succeeded
break;
case Activity.RESULT_CANCELED:
// The payment was canceled
// Tell the user their payment was canceled
break;
case PayPalActivity.RESULT_FAILURE:
// The payment failed -- we get the error from the EXTRA_ERROR_ID
// and EXTRA_ERROR_MESSAGE
String errorID = data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
String errorMessage = data
.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
// Tell the user their payment was failed.
}
}
regards,
Aqif Hamid
You can create you custom listener something like this :
Create a custom listener :
OnDoubleTap mListener;
// Double tap custome listenre to edit photoes
public interface OnDoubleTap {
public void onEvent(Uri imgPath, int mPos);
}
public void setDoubleTapListener(OnDoubleTap eventListener) {
mListener = eventListener;
}
Now call this wherever you want like this :
mListener.onEvent(Uri, 1));
Now whenever you call this listener this will fire in your activity where you use this listener like this :
myCanvas.setDoubleTapListener(new OnDoubleTap() {
#Override
public void onEvent(Uri imgPath, int Pos) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "LISTENER WORKING !!!", Toast.LENGTH_SHORT).show();
}
});
Where myCanvas is object of class where you create you listener.
Try this solution:
PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal(price),getResources().getString(R.string.curruncy_code), getResources().getString(R.string.app_name),
PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(CreateEventStep4.this, PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_PAYPAL_PAYMENT);
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.e("paymentExample", confirm.toJSONObject().toString());
JSONObject jsonObj=new JSONObject(confirm.toJSONObject().toString());
String paymentId=jsonObj.getJSONObject("response").getString("id");
System.out.println("payment id:-=="+paymentId);
screenShotFile = takeScreenshot(frmTemplate);
uploadImage(myEvent.getEvent_id(),screenShotFile);
} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}

get access to com.android.internal.telephony.Call

I need to get access to com.android.internal.telephony.Call.
doing so:
// Initialize the telephony framework
PhoneFactory.makeDefaultPhones (this);
// Get the default phone
Phone phone = PhoneFactory.getDefaultPhone ();
CallManager mCM = CallManager.getInstance ();
mCM.registerPhone (phone);
Call call = mCM.getFirstActiveBgCall();
but does not extend to initialize the framework.
Help me to initialize Call.
I need to read the state of the call like:
IDLE, ACTIVE, HOLDING, DIALING, ALERTING, INCOMING, WAITING, DISCONNECTED, DISCONNECTING.
You need to make use of PhoneStateListener
It will provide you the facility to have your application listen for different state of a phone call. You will need to put <uses-permission android:name="android.permission.READ_PHONE_STATE"/> in your manifest file
You can but there is a critical requirement: the application must be signed at system level, meaning you are the manufacturer.
Here is how you write a Service that will broadcast an intent for every change in the foreground call state.
/*
* This implementation uses the com.android.internal.telephony package: you have
* to extract the framework classes .jar file from the platform (or the
* emulator) to compile this code. Also, add the jar file to the external
* libraries in the Java Build Path/libraries of the android project. </p>
*
* The jar file must match the android version you are building the application
* for. Because this implementation is using the internal packages it cannot be
* guaranteed to operate on later versions of android.
*/
public class CallStateNotificationService extends Service {
private static final String LOG_TAG = CallStateNotificationService.class.getSimpleName();
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (msg.what == 101) {
CallManager callManager = CallManager.getInstance();
Call.State state = callManager.getActiveFgCallState();
Intent intent = new Intent(PhoneIntents.ACTION_PRECISE_CALL_STATE);
intent.putExtra(PhoneIntents.PRECISE_CALL_STATE, state.name());
Context context = getApplicationContext();
context.sendBroadcast(intent);
}
}
};
#Override
public void onCreate() {
super.onCreate();
try {
CallManager callManager = CallManager.getInstance();
if (callManager != null) {
callManager.registerForPreciseCallStateChanged(mHandler, 101, null);
} else {
Log.w(LOG_TAG, "Can't resolve CallManager reference"); //$NON-NLS-1$
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
CallManager callManager = CallManager.getInstance();
if (callManager != null) {
callManager.unregisterForPreciseCallStateChanged(mHandler);
} else {
Log.w(LOG_TAG, "Can't resolve CallManager reference"); //$NON-NLS-1$
}
}
And here is the definition of the custom broadcasted intents.
/** Intent action and extra argument names for CallStateNotificationService */
public final class PhoneIntents {
public static final String ACTION_PRECISE_CALL_STATE = "com.myorg.myapp.CALL_STATE";
public static final String PRECISE_CALL_STATE = "precise_call_state";
}
To have this code compile and link, you of course need to either build the program as part of the android distribution itself or import the class-framework by a method explained elsewhere on the Internet.
All of this is currently in an app under production.

Categories

Resources