unable to set useridentity in Mobilefirst [duplicate] - ibm-mobilefirst

I am trying assign a userid to user and I am getting error . I am following as steps below.
server details.
<realm loginModule="AuthLoginModule" name="AuthRealm">
<className>com.worklight.integration.auth.AdapterAuthenticator</className>
<parameter name="login-function" value="AuthAdapter.onAuthRequired"/>
<parameter name="logout-function" value="AuthAdapter.onLogout"/>
</realm>
</realms>
<loginModule name="AuthLoginModule">
<className>com.worklight.core.auth.ext.NonValidatingLoginModule</className>
</loginModule>
<customSecurityTest name="AuthSecurityTest">
<test isInternalUserID="true" realm="AuthRealm"/>
</customSecurityTest>
Adapter
function onAuthRequired(headers, errorMessage){
errorMessage = errorMessage ? errorMessage : null;
return {
authStatus: "credentialsRequired",
errorMessage: errorMessage
};
}
function submitAuthentication(username, password){
// if (username==="user" && password === "password"){
var userIdentity = {
userId: username,
displayName: username,
attributes: {
foo: "bar"
}
};
WL.Server.setActiveUser("AuthRealm", userIdentity);
return {
authStatus: "complete"
};
// }
// return onAuthRequired(null, "Invalid login credentials");
}
function getSecretData(){
return {
secretData: "Very very very very secret data"
};
}
function onLogout(){
WL.Logger.debug("Logged out");
}
Adapter xml
<procedure name="submitAuthentication" securityTest="wl_unprotected" />
<procedure name="getSecretData" securityTest="AuthSecurityTest"/>
Android code:
public class MFPInitializer {
Context mContext;
public AndroidChallengeHandler challengeHandler;
private String realm = "AuthRealm";
WLClient client = null;
private static MFPInitializer mfpInitializer = new MFPInitializer();
/* A private Constructor prevents any other
* class from instantiating.
*/
private MFPInitializer() {
}
/* Static 'instance' method */
public static MFPInitializer getInstance() {
return mfpInitializer;
}
void mfpConnector(WLClient client) {
challengeHandler = new AndroidChallengeHandler(realm);
client.registerChallengeHandler(challengeHandler);
client.connect(new WLResponseListener() {
#Override
public void onSuccess(WLResponse wlResponse) {
Log.d("Success--- MFP_connect", wlResponse.getResponseText());
}
#Override
public void onFailure(WLFailResponse wlFailResponse) {
Log.d("fail-- MFP_connect", wlFailResponse.getErrorMsg());
}
});
}
public void logout() {
if (client != null) {
client.logout(realm, new WLRequestListener() {
#Override
public void onSuccess(WLResponse wlResponse) {
}
#Override
public void onFailure(WLFailResponse wlFailResponse) {
}
});
}
}
public WLClient mfpInit(Context context) {
mContext = context;
try {
client = WLClient.createInstance(context);
if (client != null) {
mfpConnector(client);
}
} catch (Exception e) {
e.printStackTrace();
}
return client;
}
public static void registerUser() {
try {
URI adapterPath = new URI("/adapters/AuthAdapter/getSecretData");
WLResourceRequest request = new WLResourceRequest(adapterPath, WLResourceRequest.GET);
request.setQueryParameter("params", "[]");
request.send(new WLResponseListener() {
#Override
public void onSuccess(WLResponse wlResponse) {
Log.d("onsuccess--------", wlResponse.getResponseText());
}
#Override
public void onFailure(WLFailResponse wlFailResponse) {
Log.d("onfail--------", wlFailResponse.getErrorMsg());
}
});
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
Android challenge Handler
public class AndroidChallengeHandler extends ChallengeHandler {
// private Activity parentActivity;
private WLResponse cachedResponse;
public AndroidChallengeHandler( String realm) {
super(realm);
// parentActivity = activity;
}
#Override
public void onFailure(WLFailResponse response) {
try {
submitFailure(response);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSuccess(WLResponse response) {
submitSuccess(response);
}
#Override
public boolean isCustomResponse(WLResponse response) {
try {
if(response!= null &&
response.getResponseJSON()!=null &&
!response.getResponseJSON().isNull("authStatus") &&
response.getResponseJSON().getString("authStatus") != ""){
return true;
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
#Override
public void handleChallenge(WLResponse response){
cachedResponse = response;
Log.d( "handleChallenge: ---- ",response.getResponseText());
try {
if(response.getResponseJSON().getString("authStatus").equals("credentialsRequired")){
// MainAdapterBasedAuth.setMainText("handleChallenge->credentialsRequired");
// Intent login = new Intent(parentActivity, LoginAdapterBasedAuth.class);
// parentActivity.startActivityForResult(login, 1);
}
else if(response.getResponseJSON().getString("authStatus").equals("complete")){
Log.d( "handleChallenge: ---- ",response.getResponseText());
submitSuccess(cachedResponse);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void submitLogin( String userName, String password){
Object[] parameters = new Object[]{userName, password};
WLProcedureInvocationData invocationData = new WLProcedureInvocationData("AuthAdapter", "submitAuthentication");
invocationData.setParameters(parameters);
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(30000);
submitAdapterAuthentication(invocationData, options);
}
}
Intally in activity 1 a I am calling, which will initialize wlclient and adding realm.
MFPInitializer.getInstance().mfpInit(getApplicationContext());
But when I am trying to submit the login to setuser to device in mobile first platform my app crashes
MFPInitializer mfpInitializer= MFPInitializer.getInstance();
mfpInitializer.challengeHandler.submitLogin("user","Passcode");
I am getting following errors
on android monitor.
ava.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.worklight.wlclient.WLRequest.shouldFailOnChallengeCancel()' on a null object reference
on eclipse(MFP)
An error occurred while invoking procedure [project _MFP]AuthAdapter/submitAuthenticationFWLSE0100E: parameters: [project _MFP]
Cannot change identity of an already logged in user in realm 'AuthRealm'. The application must logout first.
FWLSE0101E: Caused by: [pro
The above mentioned error got resolved but the new userid is not getting updated In the mobilefirst console.
Can you please help me where I am doing mistake.

As mentioned in the comments, this problem was resolved by updating to the latest available iFix release from the IBM Fix Central website.

Related

Retrofit error response handling

I am using retrofit 2.3.0 to consume API's in my app but a week ago I started receiving error message and existing code was not able to display error message in UI.
Previously, I was using errorBody.toString() then suddenly after few months I got error and then last week I tried with errorBody.string() but it dodn't work. Now today it's working.
I have attached screenshots of response from server and my error handling also. Here is my code to display error message.
private static void showToastForError(retrofit2.Response<Object> response, int requestType) {
if (response != null && response.errorBody() != null) {
try {
JSONObject jObjError = null;
try {
jObjError = new JSONObject(response.errorBody() != null ? response.errorBody().toString() : "");
Toast.makeText(Application.getAppContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think you should custom call adapter to handle error.
Here my custom adapter
public final class ErrorHandlingAdapter {
/**
* A callback which offers granular callbacks for various conditions.
*/
public interface MyCallback<T> {
/**
* Called for [200, 300) responses.
*/
void success(Response<T> response);
/**
* Called for 401 responses.
*/
void unauthenticated(Response<?> response);
/**
* Called for [400, 500) responses, except 401.
*/
void clientError(Response<?> response);
/**
* Called for [500, 600) response.
*/
void serverError(Response<?> response);
/**
* Called for network errors while making the call.
*/
void networkError(IOException e);
/**
* Called for unexpected errors while making the call.
*/
void unexpectedError(Throwable t);
}
public interface MyCall<T> {
void cancel();
void enqueue(MyCallback<T> callback);
MyCall<T> clone();
boolean isExcute();
}
public static class ErrorHandlingCallAdapterFactory extends CallAdapter.Factory {
#Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations,
Retrofit retrofit) {
if (getRawType(returnType) != MyCall.class) {
return null;
}
if (!(returnType instanceof ParameterizedType)) {
throw new IllegalStateException(
"MyCall must have generic type (e.g., MyCall<ResponseBody>)");
}
Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType);
Executor callbackExecutor = retrofit.callbackExecutor();
return new ErrorHandlingCallAdapter<>(responseType, callbackExecutor);
}
private static final class ErrorHandlingCallAdapter<R> implements CallAdapter<R> {
private final Type responseType;
private final Executor callbackExecutor;
ErrorHandlingCallAdapter(Type responseType, Executor callbackExecutor) {
this.responseType = responseType;
this.callbackExecutor = callbackExecutor;
}
#Override
public Type responseType() {
return responseType;
}
#Override
public <R1> R adapt(Call<R1> call) {
return (R) new MyCallAdapter(call, callbackExecutor);
}
}
}
/**
* Adapts a {#link Call} to {#link MyCall}.
*/
static class MyCallAdapter<T> implements MyCall<T> {
private final Call<T> call;
private final Executor callbackExecutor;
MyCallAdapter(Call<T> call, Executor callbackExecutor) {
this.call = call;
this.callbackExecutor = callbackExecutor;
}
#Override
public void cancel() {
call.cancel();
}
#Override
public void enqueue(final MyCallback<T> callback) {
call.enqueue(new Callback<T>() {
#Override
public void onResponse(Call<T> call, Response<T> response) {
// on that executor by submitting a Runnable. This is left as an exercise for the reader.
callbackExecutor.execute(new Runnable() {
#Override
public void run() {
int code = response.code();
if (code >= 200 && code < 300) {
callback.success(response);
} else if (code == 401) {
if (Storage.getInstance().isLogin())
Storage.getInstance().logout(App.self().getApplicationContext());
} else if (code >= 400 && code < 500) {
callback.clientError(response);
} else if (code >= 500 && code < 600) {
callback.serverError(response);
} else {
callback.unexpectedError(new RuntimeException("Unexpected response " + response));
}
}
});
}
#Override
public void onFailure(Call<T> call, Throwable t) {
// on that executor by submitting a Runnable. This is left as an exercise for the reader.
callbackExecutor.execute(new Runnable() {
#Override
public void run() {
if (t instanceof IOException) {
if (call.isCanceled()) {
return;
}
callback.networkError((IOException) t);
Toast.makeText(App.self(), R.string.error_no_connect_internet, Toast.LENGTH_SHORT).show();
} else {
callback.unexpectedError(t);
}
}
});
}
});
}
#Override
public MyCall<T> clone() {
return new MyCallAdapter<>(call.clone(), callbackExecutor);
}
#Override
public boolean isExcute() {
return call.isExecuted();
}
}
}
Here my config to add custom call adapter
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addCallAdapterFactory(new ErrorHandlingAdapter.ErrorHandlingCallAdapterFactory()) // custom call adapter
.addConverterFactory(GsonConverterFactory.create())
.client(getHeader())
.build();
And handle request, ex:
#GET("api/getSomething")
ErrorHandlingAdapter.MyCall<BaseResponse> getSomething(#Query("param"),...)
Handle response:
ErrorHandlingAdapter.MyCall<BaseResponse> mCalls = ApiUtils.getSomething(...);
mCalls.enqueue(new ErrorHandlingAdapter.MyCallback<BaseResponse>() {
#Override
public void success(Response<BaseResponse> response) {
//handle response
}
#Override
public void unauthenticated(Response<?> response) {
//handle unauthenticated error
}
#Override
public void clientError(Response<?> response) {
//handle clientError error
}
#Override
public void serverError(Response<?> response) {
//handle serverError error
}
#Override
public void networkError(IOException e) {
//handle networkError error
}
#Override
public void unexpectedError(Throwable t) {
//handle unexpectedError error
}
}

Pusher with Service application on Android dose not bind events

I had a problem with Pusher with Service application on Android.
When I using pusher on Application or Activity then It's working.
But I move it to Service and register with application in manifress like:
<service android:name=".services.PusherServices"/>
It's not working.
When i startService Pusher connected success with authorization, but It's not bind events when I call method for register Channel.
PusherServices.java
package vn.hemlock.winkle.pancake.services;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import com.pusher.client.Pusher;
import com.pusher.client.PusherOptions;
import com.pusher.client.channel.PrivateChannel;
import com.pusher.client.channel.PrivateChannelEventListener;
import com.pusher.client.connection.ConnectionEventListener;
import com.pusher.client.connection.ConnectionState;
import com.pusher.client.connection.ConnectionStateChange;
import com.pusher.client.util.HttpAuthorizer;
import net.windjs.android.utils.Encrypt;
import net.windjs.android.utils.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import vn.hemlock.winkle.pancake.abstracts.ChatEvents;
import vn.hemlock.winkle.pancake.contracts.ServicesURI;
import vn.hemlock.winkle.pancake.ui.Conversation;
import vn.hemlock.winkle.pancake.ui.Message;
import vn.hemlock.winkle.pancake.ui.Page;
/**
* Created by me866chuan on 5/4/15.
*/
public class PusherServices extends Service {
private String LOG_TAG = "Pusher Services";
private boolean pusherOn = false;
public final String PUSHER_KEY = "...";
private String userToken = "";
private String userID = "";
private final IBinder mBinder = new LocalBinder();
public boolean isPusherOn() {
return pusherOn;
}
public void setPusherOn(boolean pusherOn) {
this.pusherOn = pusherOn;
}
public String getUserToken() {
return userToken;
}
public void setUserToken(String userToken) {
this.userToken = userToken;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
#Override
public IBinder onBind(Intent intent) {
setUserID(intent.getStringExtra("userId"));
setUserToken(intent.getStringExtra("userToken"));
startPusher();
startService(intent);
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
Log.e(LOG_TAG, "OFF");
stopService(intent);
return true;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
pusher.disconnect();
}
private Pusher pusher;
public void startPusher() {
HashMap<String, String> hash = new HashMap<>();
Log.e(LOG_TAG, "Token: "+getUserToken());
hash.put("authorization", getUserToken());
HttpAuthorizer authorizer = new HttpAuthorizer(ServicesURI.PUSHER_AUTHORIZER);
authorizer.setHeaders(hash);
PusherOptions options = new PusherOptions().setAuthorizer(authorizer);
pusher = new Pusher(PUSHER_KEY, options);
pusher.connect(new ConnectionEventListener() {
#Override
public void onConnectionStateChange(ConnectionStateChange change) {
Log.e(LOG_TAG, "State changed to " + change.getCurrentState() +
" from " + change.getPreviousState());
if(change.getCurrentState().toString().toUpperCase().equals("CONNECTED") || change.getCurrentState().toString().toUpperCase().equals("CONNECTING")){
setPusherOn(true);
}
else setPusherOn(false);
}
#Override
public void onError(String message, String code, Exception e) {
Log.e(LOG_TAG, "There was a problem connecting: " + message);
}
}, ConnectionState.ALL);
}
PrivateChannel userChannel;
public void userListenChanel(final Activity activity) {
if (pusher == null) return;
userChannel = pusher.subscribePrivate("private-" + Encrypt.stringMD5(getUserID()));
userChannel.bind("fetch_accounts", new PrivateChannelEventListener() {
#Override
public void onEvent(String channel, String event, final String data) {
Log.e(LOG_TAG, "Received event with data: " + data);
if (activity != null) activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
ChatEvents.getInstance().onNewPage(new Page((new JSONObject(data)).getJSONObject("page")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onAuthenticationFailure(String s, Exception e) {
Log.e(LOG_TAG, "USER FETCH FAIL: " + s);
}
#Override
public void onSubscriptionSucceeded(String s) {
Log.e(LOG_TAG, "USER FETCH SUCCESS: " + s);
}
});
}
PrivateChannel pageChannel;
private String idPageChannelListen;
public void pageListenChanel(final Activity activity, String pageId) {
if (pusher == null) return;
idPageChannelListen = pageId;
Log.e(LOG_TAG, "Channel page: "+"private-" + Encrypt.stringMD5(pageId));
pageChannel = pusher.subscribePrivate("private-" + Encrypt.stringMD5(pageId));
pageChannel.bind("realtime_updates", new PrivateChannelEventListener() {
#Override
public void onEvent(String channel, String event, final String data) {
Log.e(LOG_TAG, "Real time update with data: " + data);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(data);
} catch (JSONException e) {
e.printStackTrace();
}
final JSONObject finalJsonObject = jsonObject;
if(activity != null) activity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (finalJsonObject == null) return;
try {
if (finalJsonObject.has("message")) ChatEvents.getInstance().onNewMessage(new Message(finalJsonObject.getJSONObject("message")));
else if (finalJsonObject.has("conversation")) ChatEvents.getInstance().onNewConversation(new Conversation(finalJsonObject.getJSONObject("conversation")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onAuthenticationFailure(String s, Exception e) {
Log.e(LOG_TAG, "Real time update failed: " + s);
}
#Override
public void onSubscriptionSucceeded(String s) {
Log.e(LOG_TAG, "Real time update successed: " + s);
}
});
pageChannel.bind("fetch_conversations", new PrivateChannelEventListener() {
#Override
public void onEvent(String channel, String event, final String data) {
Log.e(LOG_TAG, "Received event with data: " + data);
if(activity != null) activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
ChatEvents.getInstance().onNewConversation(new Conversation((new JSONObject(data)).getJSONObject("conversation")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onAuthenticationFailure(String s, Exception e) {
}
#Override
public void onSubscriptionSucceeded(String s) {
}
});
pageChannel.bind("fetch_comments", new PrivateChannelEventListener() {
#Override
public void onEvent(String channel, String event, String data) {
Log.e(LOG_TAG, "Received event with data: " + data);
}
#Override
public void onAuthenticationFailure(String s, Exception e) {
}
#Override
public void onSubscriptionSucceeded(String s) {
}
});
}
public void removeLisnterPage(String pageId) {
if (pusher != null) pusher.unsubscribe("private-" + Encrypt.stringMD5(pageId));
idPageChannelListen = "";
}
public void reconnectPusher() {
if (pusher != null) {
pusher.disconnect();
pusher.connect();
}
}
public void disconnectPusher() {
if (pusher != null) pusher.disconnect();
}
public String getIdPageChannelListen() {
return idPageChannelListen;
}
public class LocalBinder extends Binder {
public PusherServices getService() {
// Return this instance of LocalService so clients can call public methods
return PusherServices.this;
}
}
}

GoogleAuthUtil.getToken return null and getting com.google.android.gms.auth.GoogleAuthException: Unknown genrated

This my code:
Main Activity:
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "PlayHelloActivity";
// This client id
public static String TYPE_KEY = "997914232893-4f2dggarutugl7r945jblef441mia28f.apps.googleusercontent.com";
private static final String SCOPE = "audience:server:client_id:"+TYPE_KEY+":api_scope:https://www.googleapis.com/auth/userinfo.profile";
private String mEmail;
ProgressDialog mDialog;
String providerName;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.sign_in_button).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getUsername();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
if (resultCode == RESULT_OK) {
mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
Log.e("email", ""+mEmail);
getUsername();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "You must pick an account", Toast.LENGTH_SHORT).show();
}
} else if ((requestCode == REQUEST_CODE_RECOVER_FROM_AUTH_ERROR ||
requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
&& resultCode == RESULT_OK) {
handleAuthorizeResult(resultCode, data);
return;
}
}
/** Attempt to get the user name. If the email address isn't known yet,
* then call pickUserAccount() method so the user can pick an account.
*/
private void getUsername() {
if (mEmail == null) {
pickUserAccount();
} else {
if (isDeviceOnline()) {
new GetNameInForeground(MainActivity.this, mEmail, SCOPE).execute();
} else {
Toast.makeText(this, "No network connection available", Toast.LENGTH_SHORT).show();
}
}
}
/** Starts an activity in Google Play Services so the user can pick an account */
private void pickUserAccount() {
String[] accountTypes = new String[]{"com.google"};
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
accountTypes, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
}
/** Checks whether the device currently has a network connection */
private boolean isDeviceOnline() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
private void handleAuthorizeResult(int resultCode, Intent data) {
if (data == null) {
// show("Unknown error, click the button again");
return;
}
if (resultCode == RESULT_OK) {
Log.i(TAG, "Retrying");
new GetNameInForeground(MainActivity.this, mEmail, SCOPE).execute();
return;
}
if (resultCode == RESULT_CANCELED) {
// show("User rejected authorization.");
return;
}
// show("Unknown error, click the button again");
}
/**
* This method is a hook for background threads and async tasks that need to provide the
* user a response UI when an exception occurs.
*/
public void handleException(final Exception e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (e instanceof GooglePlayServicesAvailabilityException) {
// The Google Play services APK is old, disabled, or not present.
// Show a dialog created by Google Play services that allows
// the user to update the APK
int statusCode = ((GooglePlayServicesAvailabilityException)e)
.getConnectionStatusCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode,
MainActivity.this,
REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
dialog.show();
} else if (e instanceof UserRecoverableAuthException) {
// Unable to authenticate, such as when the user has not yet granted
// the app access to the account, but the user can fix this.
// Forward the user to an activity in Google Play services.
Intent intent = ((UserRecoverableAuthException)e).getIntent();
startActivityForResult(intent,
REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
}
}
});
}
}
This is requst for getting token :
public class GetNameInForeground extends AbstractGetNameTask {
private static final String REQUEST_CODE_AUTH_GOOGLE_ACCOUNT = null;
public GetNameInForeground(MainActivity activity, String email, String scope) {
super(activity, email, scope);
}
/**
* Get a authentication token if one is not available. If the error is not recoverable then
* it displays the error message on parent activity right away.
*/
#Override
protected String fetchToken() throws IOException {
try {
String token= GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
return token;
} catch ( UserRecoverableAuthException userRecoverableException) {
mActivity.handleException(userRecoverableException);
} catch ( GoogleAuthException fatalException) {
onError("Unrecoverable error" + fatalException.getMessage(), fatalException);
}
catch (IOException e) {
// TODO: handle exception
}
return null;
}
}
If I'm not using client id in scope url then I'll get details of only my account (in which you have register in google developer account)then what is the use of client id.

Estimote : Show notification when the app is closed

How to show notification when the app is closed with estimote api.As it is having default BeaconService we need to implement it in the application level to show the notification when the app is closed.So for that i'm trying with the following code.
Activity:-
public class Dashboard extends Activity {
private static final String TAG = Dashboard.class.getSimpleName();
ConnectionDetector cDetector;
private static final int NOTIFICATION_ID = 123;
private NotificationManager notificationManager;
JSONParser jParser = new JSONParser();
AlertDialogManager alert;
private static final String URL_NOTIFICATIONS = "";
ArrayList<NameValuePair> pairs;
private static final int REQUEST_ENABLE_BT = 1234;
private ProgressDialog pDialog;
private BeaconManager bManager;
// private Beacon beacon;
private Region region = new Region("regionID", null, null, null);
List<Beacon> beaconList;
BroadcastReceiver receiver;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_demo);
getActionBar().setDisplayHomeAsUpEnabled(true);
cDetector = new ConnectionDetector(getApplicationContext());
// check Internet connection
if (!cDetector.isConnectingToInternet()) {
alert.showAlertDialog(this, "Internet Connection Error",
"Please connect to working internet connection", false);
return;
}
bManager = new BeaconManager(getApplicationContext());
bManager.setRangingListener(new BeaconManager.RangingListener() {
#Override
public void onBeaconsDiscovered(Region region,
final List<Beacon> beacons) {
// Note that results are not delivered on UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
// Note that beacons reported here are already sorted by
// estimated distance between device and beacon.
getActionBar().setSubtitle(
"Found beacons: " + beacons.size());
}
});
}
});
Log.i("BeaconsList", "beaconslist" + beaconList);
// region = new Region("regionId", ((Beacon)
// beaconList).getProximityUUID(),
// ((Beacon) beaconList).getMajor(),
// ((Beacon) beaconList).getMinor());
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Default values are 5s of scanning and 25s of waiting time to save CPU
// cycles.In order for this demo to be more responsive and immediate we
// lower down those values.
bManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
bManager.setMonitoringListener(new MonitoringListener() {
#Override
public void onEnteredRegion(Region arg0, List<Beacon> arg1) {
// TODO Auto-generated method stub
postNotification("Welcome to Walmart !Today there is 10% off on all Goods.");
// new GetNotificationData().execute();
}
#Override
public void onExitedRegion(Region arg0) {
// TODO Auto-generated method stub
postNotification("Exit region");
}
});
}
#Override
protected void onStart() {
super.onStart();
// Check if device supports Bluetooth Low Energy.
if (!bManager.hasBluetooth()) {
Toast.makeText(this, "Device does not have Bluetooth Low Energy",
Toast.LENGTH_LONG).show();
return;
}
// If Bluetooth is not enabled, let user enable it.
if (!bManager.isBluetoothEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
connectToService();
}
}
#Override
protected void onStop() {
try {
bManager.stopRanging(region);
} catch (RemoteException e) {
Log.d(TAG, "Error while stopping ranging", e);
}
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_OK) {
connectToService();
} else {
Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG)
.show();
getActionBar().setSubtitle("Bluetooth not enabled");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void connectToService() {
getActionBar().setSubtitle("Scanning...");
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startRanging(region);
} catch (RemoteException e) {
Toast.makeText(
Dashboard.this,
"Cannot start ranging, something terrible happened",
Toast.LENGTH_LONG).show();
Log.e(TAG, "Cannot start ranging", e);
}
}
});
}
#Override
protected void onResume() {
super.onResume();
notificationManager.cancel(NOTIFICATION_ID);
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startMonitoring(region);
} catch (RemoteException e) {
Log.d(TAG, "Error while starting monitoring");
}
}
});
}
#Override
protected void onDestroy() {
notificationManager.cancel(NOTIFICATION_ID);
bManager.disconnect();
super.onDestroy();
}
private void postNotification(String msg) {
Intent notifyIntent = new Intent(Dashboard.this, Dashboard.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(
Dashboard.this, 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(Dashboard.this)
.setSmallIcon(R.drawable.beacon_gray)
.setContentTitle("Notify Demo").setContentText(msg)
.setAutoCancel(true).setContentIntent(pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(NOTIFICATION_ID, notification);
TextView statusTextView = (TextView) findViewById(R.id.status);
statusTextView.setText(msg);
}
}
Application Class:-
public class MyApplication extends Application {
BeaconManager bManager;
NotificationManager notificationManager;
private Region region = new Region("regionID", null, null, null);
private static final int NOTIFICATION_ID = 123;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
bManager = new BeaconManager(getApplicationContext());
bManager.setRangingListener(new BeaconManager.RangingListener() {
#Override
public void onBeaconsDiscovered(Region regions, List<Beacon> beacons) {
// TODO Auto-generated method stub
Log.i("Beacons", "" + beacons.size());
}
});
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startMonitoring(region);
} catch (RemoteException e) {
Log.d("BEACON", "Error while starting monitoring");
}
}
});
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Default values are 5s of scanning and 25s of waiting time to save CPU
// cycles.In order for this demo to be more responsive and immediate we
// lower down those values.
bManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
bManager.setMonitoringListener(new MonitoringListener() {
#Override
public void onEnteredRegion(Region arg0, List<Beacon> arg1) {
// TODO Auto-generated method stub
postNotification("Welcome to Walmart !Today there is 10% off on all Goods.");
}
#Override
public void onExitedRegion(Region arg0) {
// TODO Auto-generated method stub
postNotification("Exit region");
}
});
}
private void postNotification(String msg) {
Intent notifyIntent = new Intent(getApplicationContext(),
Dashboard.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(
getApplicationContext(), 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(
getApplicationContext()).setSmallIcon(R.drawable.beacon_gray)
.setContentTitle("Notify Demo").setContentText(msg)
.setAutoCancel(true).setContentIntent(pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(NOTIFICATION_ID, notification);
}
}
and i have mentioned the beaconservice in manifest also as follows..
Can any one help what is going wrong here and how can show the notification when the app is closed.

calling alarm from a service

I designed my service as it will make an alarm when user will go to a certain location.
But it crashes when it go to the certain making the alarm.
public class CheckDestinationService extends Service {
Calendar calender;
double late,longe;
int dis;
String loc;
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location) {
mLastLocation.set(location);
final double currlat;
final double currlong;
float[] DistanceArray = new float[1];
currlat = location.getLatitude();
currlong = location.getLongitude();
android.location.Location.distanceBetween(currlat,currlong,late,longe,DistanceArray);
float Distance = DistanceArray[0];
//Toast.makeText(getApplicationContext(), "asdf "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
Log.d("asdfasdas", String.valueOf(currlat)+","+String.valueOf(currlong)+" "+String.valueOf(Distance));
if (Distance<=dis && Distance!=0 && dis!=0)
{
dis = 0;
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Toast.makeText(getApplicationContext(), "Reached "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(),pendingIntent);
//stopSelf();
}
/*final Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
// TODO Auto-generated method stub
Intent intent = null;
intent.putExtra("lat", currlat);
intent.putExtra("long", currlong);
intent.putExtra("dis", dis);
intent.putExtra("loc", loc);
Toast.makeText(getApplicationContext(), "Sending", Toast.LENGTH_SHORT).show();
sendBroadcast(intent);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);*/
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
late = intent.getDoubleExtra("lat", 0);
longe = intent.getDoubleExtra("long", 0);
dis = intent.getIntExtra("dis", 0);
loc = intent.getStringExtra("loc");
Toast.makeText(getApplicationContext(), "Destination Set to: "+loc+
" and Minimum Distance: "+
String.valueOf(dis) , Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onCreate() {
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "Service Destroyed", Toast.LENGTH_SHORT).show();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
}
}
}
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
and my AlarmReceiver class is
public class AlarmReceiver extends Activity {
private MediaPlayer mMediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.alarmreceiver);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
stopAlarm.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (IOException e) {
System.out.println("OOPS");
}
}
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
#Override
public void onBackPressed() {
//MainActivity.iMinDistance = 0;
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
}
}
I tested AlarmReceiver class from other activites and it worked properly
but it not working from the service.
please help!!
initalize Calendar
calender = Calendar.getInstance()