Authenticate Android App - android

I am new to android and I am building an app that I want to authenticate using the local users google account. Unfortunately I have gotten myself in a bit of a bind looking at Auth 2.0 and logging in via the google services.
What is the recommended route to authenticate (and hopefully not require typing a login name)? I tried many of the samples that I saw but much of it seems deprecated.
Any example code would be very helpful as well.
I was using this tutorial but it is a bit outdated and I believe that it is much simplier now.
http://blog.notdot.net/2010/05/Authenticating-against-App-Engine-from-an-Android-app
Thanks,
Craig

Here is how I solved it. Don't know if it is the recommended approach but it works...
in OnCreate of my entry activity (main) I put...
AccountManager accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");
AccountManagerFuture<Bundle> futur;
futur = accountManager.getAuthToken(accounts[0],AUTH_TOKEN_TYPE_USERINFO_PROFILE, null, null,
new OnTokenAcquired(), new Handler(new OnError()));
In that same activity I created...
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
// Get the result of the operation from the AccountManagerFuture.
Bundle bundle;
try {
bundle = result.getResult();
// The token is a named value in the bundle. The name of the
// value
// is stored in the constant AccountManager.KEY_AUTHTOKEN.
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
//If token isn't null then let them in and also make sure Crunchy accounts are created
if(token!=null){
ProcessToken pt = new ProcessToken(token);
pt.execute("");
}
Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 0);
return;
}
}catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I also created an asyncTask to process the token (because I do a bit more logic to setup account and set a cookie). It looks like this (much of my processing/cookie logic is not completed yet)
package com.craig.activities.login;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
import android.util.Log;
public class ProcessToken extends AsyncTask<String,Integer,Long>{
private static final String AUTH_ACCESS_TOKEN_URL = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=";
private static final String DEBUG_TAG = "OnTokenAcquired.class";
private static String token="";
public ProcessToken(String tokenValue){
token=tokenValue;
}
#Override
protected Long doInBackground(String... params) {
try {
URL url = new URL(AUTH_ACCESS_TOKEN_URL+token);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int serverCode= con.getResponseCode();
if(serverCode==200){
Log.i(DEBUG_TAG, "code 200!!!");
//PUT MY LOGIC IN HERE....
}
else{
Log.i(DEBUG_TAG, "Oops, We had an error on authentication");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Not sure if this is the best but it seems to be working for me....

Related

How to get Advertising id in android?

I used this code it's working when i called from activity and fragment
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
} catch (IOException e) {
e.printStackTrace();
} catch (GooglePlayServicesAvailabilityException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
String AdId = adInfo.getId();
But when i called from pending intent like Package Removed then i want to call the web service at that time i need advertising id but i got null.if you people had done previously please suggest me.thanks in advance.
try use app context
as receivers could use activity context or app context - depends who&how started the receiver
AdvertisingIdClient.getAdvertisingIdInfo(context.getApplicationContext());
You can try this code and call the bellow method on onCreate
public void getAAID()
{
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(MyActivity.this);
String myId = adInfo != null ? adInfo.getId() : null;
Log.i("UIDMY",myId);
} catch (Exception e) {
Log.e("error", e);
}
}
});
}
Check complete post: how to get AAID programmatically

Passing a bitmap/uri to Box Android API v2

EDIT:
I wrote a function passing the Authenticated Box Client and Bitmap Bytestream. Was also informated the root directory on Box has an ID of 0. But I'm still unable to upload.
What I need to do is create a directory, if present don't and upload the file in that directory.
private void doUpload(final BoxAndroidClient client, final ByteArrayInputStream bs) {
if(client.isAuthenticated())
{
System.out.println("Trying to upload: In upload function");
AsyncTask<Null, Integer, Null> task = new AsyncTask<Null, Integer, Null>() {
#Override
protected void onPostExecute(Null result) {
Toast.makeText(PagerActivity.this, "done uploading", Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
Toast.makeText(PagerActivity.this, "start uploading", Toast.LENGTH_LONG).show();
super.onPreExecute();
}
#Override
protected Null doInBackground(Null... params) {
try {
BoxDefaultRequestObject folreqObj = new BoxDefaultRequestObject();
BoxFolder newFol = new BoxFolder();
String parentId = newFol.getId();
BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject("0", "bestphotonow.png", bs);
client.getFilesManager().uploadFile(requestObj);
/*
if(client.getFoldersManager().getFolder(parentId, folreqObj).getName()!=null)
{
BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject(parentId, "bestphotonow.png", bs);
client.getFilesManager().uploadFile(requestObj);
}
else
{
BoxFolderRequestObject upreqObj = BoxFolderRequestObject.createFolderRequestObject("BestPhotoNow", parentId);
client.getFoldersManager().createFolder(upreqObj);
BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject(parentId, "bestphotonow.png", bs);
client.getFilesManager().uploadFile(requestObj);
}*/
} catch (BoxRestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BoxJSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BoxServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthFatalFailureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
};
task.execute();
}
}
So, I have a wallpaper app that fetches some images from a server. I'm trying to integrate box to be able to upload the picture in the current view (viewpager) to Box via Box Android API v2.
https://github.com/box/box-android-sdk-v2
I have been successful to authenticate the user via oauth. But, I'm really stuck at trying to upload the bitmap or uri direct to their upload call without having to launch a folder picker activity. This is what I have.
On click of a button for upload:
case R.id.boxcloudbutton:
imageLoader.loadImage(url, new SimpleImageLoadingListener(){
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
Intent intent = OAuthActivity.createOAuthActivityIntent(getApplicationContext(), "vfoj4o6nxqblahh454wem", "J9TQWyFSblahV2C", false, "http://localhost");
intent.putExtra("boximageUri", imageUri);
System.out.println("BoxUri: "+imageUri);
startActivityForResult(intent, BOX_RESULT);
super.onLoadingComplete(imageUri, view, loadedImage);
}
});
break;
I'm trying to pass either the bitmap or uri
and in the OnActivityResult
case BOX_RESULT:
if (resultCode == Activity.RESULT_CANCELED) {
// Get the error message for why authentication failed.
String failMessage = data.getStringExtra(OAuthActivity.ERROR_MESSAGE);
// Implement your own logic to handle the error.
// handleFail(failMessage);
} else {
// You will get an authenticated oath token object back upon success.
BoxAndroidOAuthData oauth = data.getParcelableExtra(OAuthActivity.BOX_CLIENT_OAUTH);
// If you don't want to supply a customized hub or parser, use null to fall back to defaults.
BoxAndroidClient client = new BoxAndroidClient( "vfoj4oxxxxxxxxxxtordlh454wem",
"J9TjxxxxxxxmRwux2V2C", null, null, null);
client.authenticate(oauth);
System.out.println("Data for Box: "+data.getExtras().getString("boximageUri"));
BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject(0, "name", file);
BoxFile bFile = client.getFilesManager().uploadFile(requestObj);
}
break;
Here, I successfully get authenticated, but I do not recieve the uri or the bitmap in the Intent data that I passed.
More, if anyone has any idea of how I can pass bitmap to a file for a file upload for Box api v2, I would really appreciate some assistance!
Thanks,
Arnab
Try shifting around the responsibility....
When you go to the Oauth activity , do just the authentication and return the credentials or Token from that which grants permission for subsequent actions on Box api.
Choose correct api to POST a bitmap... Here you want an api call that allows the ByteArray corresponding to the bitMap to be loaded as a ByteArrayEntity in the body of a http POST action.
This answer sample of how to prepare a local bitmap instance for being wrapped in body of Post as byteArray.

Accessing a TCP socket from all activities

I want to create a TCP socket when a button is pressed in my first activity and then access that same socket object from any activity (not sure that closing and opening a socket in each activity is a good idea).
I tried quite a few methods having my mind set on a Singleton instance being the best solution to access an object though any activity, my problem is since this is a TCP socket I don't see AsyncTask as the smart idea (can only execute once, defies my point of having one instance of an object) and I don't see how I combine a regular Thread with a singleton.
Singleton code:
public class TCPSingleton extends Application {
private static TCPSingleton singleInstance;
String HostIP;
int tcp_port;
Socket clientSocket;
DataOutputStream outToServer;
public static TCPSingleton getInstance() {
return singleInstance;
}
#Override
public void onCreate() {
super.onCreate();
singleInstance = this;
singleInstance.initializeInstance();
}
protected void initializeInstance() {
this.HostIP = "10.0.0.6";
this.tcp_port = 9871;
try {
this.clientSocket = new Socket(this.HostIP, this.tcp_port);
this.outToServer = new DataOutputStream(clientSocket.getOutputStream());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void send_data(String data){
try {
this.outToServer.writeBytes(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How do I merge a thread here (or what's the better idea other than singleton to do this).

Android net.sip: manager.makeAudioCall(..) throws sip session error

I'm trying to establish a call using sip on Android. The permissions in my manifest are:
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.USE_SIP"/>
<uses-permission android:name="android.permission.INTERNET"/>
The CALL_PHONE permission is there because my app also calls regular numbers.
This is the activity code:
package x.x.x;
import java.text.ParseException;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.sip.SipAudioCall;
import android.net.sip.SipException;
import android.net.sip.SipManager;
import android.net.sip.SipProfile;
import android.os.Bundle;
import android.util.Log;
public class CallScreen extends Activity{
public SipManager manager = null;
public SipProfile me = null;
public SipAudioCall call = null;
//IncomingCallReceiver callReceiver;
String domain = "myserver.net";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.callscreen);
initManager();
Log.d("Z:","Done initManger()");
Thread waiter = new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
try {
sleep(10000);
Log.d("Z:","Done waiting");
initCall();
Log.d("Z:","Done initCall");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
waiter.start();
//initCall();
}
public void initManager()
{
manager = SipManager.newInstance(this);
initLocalProfile();
}
public void initLocalProfile()
{
String username = "user";
String password = "12345";
String domain = "myserver.net";
try {
SipProfile.Builder builder = new SipProfile.Builder(username,domain);
builder.setPassword(password);
me = builder.build();
//Intent intent = new Intent();
//PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA);
//manager.open(me,pi,null);
manager.open(me);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SipException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void initCall()
{
SipAudioCall.Listener listener = new SipAudioCall.Listener(){
#Override
public void onCallEstablished(SipAudioCall call) {
// TODO Auto-generated method stub
//super.onCallEstablished(call);
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
}
#Override
public void onCallEnded(SipAudioCall call) {
// TODO Auto-generated method stub
super.onCallEnded(call);
}
};
try {
call = manager.makeAudioCall(me.getUriString(), "12345678910", listener, 30);
} catch (SipException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The error shown on logcat:
01-26 22:20:25.710: D/SipAudioCall(31060): sip session error: CLIENT_ERROR: libcore.io.ErrnoException: getaddrinfo failed: ENOENT (No such file or directory)
I'm trying to make this tiny example work before i organize this code a little differently (username and pass not hard-coded, for example). I'm also not very familier with sip. Really appriciate any advice.
any ideas? Thanks!
The problem is on the following line:
call = manager.makeAudioCall(me.getUriString(), "12345678910", listener, 30);
The second parameter of makeAudioCall method must be the URI of the SIP profile to make the call to, but you provided only its username (i.e: "12345678910"). Change it to something like:
call = manager.makeAudioCall(me.getUriString(), "sip:12345678910#myserver.net", listener, 30);

Facebook wall post from multiple Activities

I have been trying to make wall post from multiple pages but when i try to make post from other pages except original facebook page, it is giving me an exception of java.lang.NullPointerException
The method i am calling and created in a Facebook page.
public void setConnection() {
mContext = this;
mFacebook = new Facebook(getResources().getString(R.string.FACEBOOK_ID_TEST));
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
}
public boolean isSession() {
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
String access_token = sharedPrefs.getString("access_token", "x");
Long expires = sharedPrefs.getLong("access_expires", -1);
Log.d(TAG, access_token);
if (access_token != null && expires != -1) {
mFacebook.setAccessToken(access_token);
mFacebook.setAccessExpires(expires);
}
return mFacebook.isSessionValid();
}
public void getID()
{
Bundle bundle = new Bundle();
bundle.putString("fields", "birthday");
try {
mFacebook.request("me/friends", bundle);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Error in FaceBook Friends List","Exception = "+e.getMessage());
e.printStackTrace();
}
if (isSession()) {
Log.d(TAG, "sessionValid");
try {
mFacebook.request("me/friends", bundle);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Error in FaceBook Friends List","Exception = "+e.getMessage());
e.printStackTrace();
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
}
}
I am able to get the wall post dialog box but its showing "An error occurred. Please try again later".
Please help me out.
Thanks in advance.
I think the best way for you to achieve this would be to make an abstract class which extends the super class Activity, use this to hold all your facebook functions.
Then when you want to have an activity which has the facebook functionality then you would just extend this abstract class. If your not sure what I mean then take a look at the tutorial here, it goes through how to setup a basic Facebook Activity class. Hope this helps.

Categories

Resources