I pair device and I want to in my activity get a response of this function
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(DeviceListActivity.this, "Nie udalo się sparować urządzenia", Toast.LENGTH_LONG).show();
}
}
You need to register BroadcastReceiver.
BroadcastReceiver mBondStateBroadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if(intent.getAction() == BluetoothDevice.ACTION_BOND_STATE_CHANGED) {
// do your stuff
}
}
};
final IntentFilter bondFilter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBondStateBroadcastReceiver, bondFilter);
Related
Here is my service MyServiceSMS.java
Whenever I close my app I only receive a default toast of
broadcastreceiver "Message Recieved By : xxxxxxx"
Rest of the code is not executing below onReceiceve.
I have some task inside onReceiceve method, I want them to be executed even if the user closes the app.
public class MyServiceSMS extends Service {
private IntentFilter mIntentFilter;
private SMSGetter smsGetter;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
smsGetter = new SMSGetter();
mIntentFilter = new IntentFilter();
mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsGetter, mIntentFilter);
Toast.makeText(this, "Hello I'm a service", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onDestroy() {
super.onDestroy();
//unregisterReceiver(smsGetter);
}
public class SMSGetter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
JSONObject data = new JSONObject();
try {
data.put("from", smsMessage.getDisplayOriginatingAddress());
data.put("message", smsMessage.getMessageBody());
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
if (sharedPreferences.contains(IP) && sharedPreferences.contains(IP)) {
sendSMsToServer sendTextToServer = new sendSMsToServer();
sendTextToServer.execute(data.toString(), sharedPreferences.getString(IP, ""), sharedPreferences.getString(PORT, ""));
Toast.makeText(context, "Your Ip :" + data.toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Your IP is empty .. Scan to get IP Again ..", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(context, smsMessage.getDisplayMessageBody(), Toast.LENGTH_SHORT).show();
}
}
}
}
My Manifest
<service
android:name=".viewmodel.MyServiceSMS"
android:enabled="true"
android:exported="true"></service>
I have a function ReadConfig in non activity class which is invoked by a Service. This function uses IntentService to read data from a file.
Function in non activity class
//Start of globalVariables
public static boolean received;
public static String actionID = "ACTION_ID";
public static ArrayList<String> configData;
public static BroadcastReceiver configDataReceiver;
//End of globalVariables
public static List<String> ReadConfig(Context context, String configFileName)
{
configDataReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context arg0, Intent intent)
{
if(intent.getAction().equals(actionID))
{
configData = intent.getStringArrayListExtra("CONFIGDATA");
received = true;
}
}
};
LocalBroadcastManager.getInstance(context)
.registerReceiver(configDataReceiver,new IntentFilter(actionID));
Intent workRequest = new Intent(context,IOConfigurations.class);
workRequest.putExtra("OPERATION","READ");
workRequest.putExtra("FILENAME",configFileName);
//Calling intentservice
context.startService(workRequest);
//Wait for broadcast receiver to get data and assign to global variables
while (!received)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
LocalBroadcastManager.getInstance(context).unregisterReceiver(configDataReceiver);
return configData;
}
Intent Service
Intent configData = new Intent(actionID);
configData.putStringArrayListExtra("CONFIGDATA",FileOperations.readFile(fileName));
LocalBroadcastManager.getInstance(this).sendBroadcast(configData);
The intent service is getting invoked and broadcasts the data but the receiver however doesn't receive any data from Broadcast manager and the while loop continues for ever.
check my comments
public static List<String> ReadConfig(Context context, String configFileName)
{
configDataReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context arg0, Intent intent)
{
if(intent.getAction().equals(actionID))
{
configData = intent.getStringArrayListExtra("CONFIGDATA");
received = true;
}
}
};
LocalBroadcastManager.getInstance(context)
.registerReceiver(configDataReceiver,new IntentFilter(actionID));
Intent workRequest = new Intent(context,IOConfigurations.class);
workRequest.putExtra("OPERATION","READ");
workRequest.putExtra("FILENAME",configFileName);
//Calling intentservice
context.startService(workRequest);
//Wait for broadcast receiver to get data and assign to global variables
while (!received)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
// Why here your unregistering the broacast listener,
// Your registering and unregistering in same call, unregiter when your work is done
LocalBroadcastManager.getInstance(context).unregisterReceiver(configDataReceiver);
return configData;
}
I'm trying to create a service that will play music in the background, but when a song completes the nextone should be played but seems oncomplete listener is not called. Can anyone tell me where is the problem?
P.S. I don't get anything in logcat, and I dont get the log that should be shown when entering oncomplete listener.
Here is my code:
public class myPlayService extends Service implements OnCompletionListener,
OnPreparedListener, OnErrorListener, OnSeekCompleteListener,
OnInfoListener, OnBufferingUpdateListener {
private static final String TAG = "--";
public static MediaPlayer mediaPlayer = new MediaPlayer();
// songs
private static ArrayList<Songs> songs;
private static int position;
// Set up the notification ID
private static final int NOTIFICATION_ID = 1;
private boolean isPausedInCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
// ---Variables for seekbar processing---
String sntSeekPos;
static int intSeekPos;
int mediaPosition;
int mediaMax;
// Intent intent;
private final Handler handler = new Handler();
private static int songEnded;
public static boolean serviceStarted=false;
public static final String BROADCAST_ACTION = "com.darkovski.quran.seekprogress";
// Set up broadcast identifier and intent
public static final String BROADCAST_BUFFER = "com.darkovski.quran.broadcastbuffer";
Intent bufferIntent;
Intent seekIntent;
// Declare headsetSwitch variable
private int headsetSwitch = 1;
// OnCreate
#Override
public void onCreate() {
Log.v(TAG, "Creating Service");
// android.os.Debug.waitForDebugger();
// Instantiate bufferIntent to communicate with Activity for progress
// dialogue
serviceStarted=true;
songs = new ArrayList<Songs>();
bufferIntent = new Intent(BROADCAST_BUFFER);
// ---Set up intent for seekbar broadcast ---
seekIntent = new Intent(BROADCAST_ACTION);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.reset();
// Register headset receiver
registerReceiver(headsetReceiver, new IntentFilter(
Intent.ACTION_HEADSET_PLUG));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// get songs and position
songs = new ArrayList<Songs>();
songs = (ArrayList<Songs>) intent.getSerializableExtra("songs");
Log.v("--", songs.size() + " size!#$");
position = intent.getIntExtra("position", -1);
// ---Set up receiver for seekbar change ---
registerReceiver(broadcastReceiver, new IntentFilter(
Player.BROADCAST_SEEKBAR));
// Manage incoming phone calls during playback. Pause mp on incoming,
// resume on hangup.
// -----------------------------------------------------------------------------------
// Get the telephony manager
Log.v(TAG, "Starting telephony");
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Log.v(TAG, "Starting listener");
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
// String stateString = "N/A";
Log.v(TAG, "Starting CallStateChange");
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mediaPlayer != null) {
pauseMedia();
isPausedInCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Phone idle. Start playing.
if (mediaPlayer != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
break;
}
}
};
// Register the listener with the telephony manager
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
// Insert notification start
initNotification();
mediaPlayer.reset();
// Set up the MediaPlayer data source using the strAudioLink value
if (!mediaPlayer.isPlaying()) {
try {
// Send message to Activity to display progress dialogue
sendBufferingBroadcast();
mediaPlayer.setDataSource(songs.get(position).getLink());
;
// Prepare mediaplayer
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
// --- Set up seekbar handler ---
setupHandler();
return START_STICKY;
}
// ---Send seekbar info to activity----
private void setupHandler() {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 300); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
// // Log.d(TAG, "entered sendUpdatesToUI");
LogMediaPosition();
handler.postDelayed(this, 1000); // 2 seconds
}
};
private void LogMediaPosition() {
// // Log.d(TAG, "entered LogMediaPosition");
if (mediaPlayer.isPlaying()) {
mediaPosition = mediaPlayer.getCurrentPosition();
// if (mediaPosition < 1) {
// Toast.makeText(this, "Buffering...", Toast.LENGTH_SHORT).show();
// }
mediaMax = mediaPlayer.getDuration();
// seekIntent.putExtra("time", new Date().toLocaleString());
seekIntent.putExtra("counter", String.valueOf(mediaPosition));
seekIntent.putExtra("mediamax", String.valueOf(mediaMax));
seekIntent.putExtra("song_ended", String.valueOf(songEnded));
sendBroadcast(seekIntent);
}
}
// --Receive seekbar position if it has been changed by the user in the
// activity
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateSeekPos(intent);
}
};
// Update seek position from Activity
public void updateSeekPos(Intent intent) {
int seekPos = intent.getIntExtra("seekpos", 0);
if (mediaPlayer.isPlaying()) {
handler.removeCallbacks(sendUpdatesToUI);
mediaPlayer.seekTo(seekPos);
setupHandler();
}
}
// ---End of seekbar code
// If headset gets unplugged, stop music and service.
private BroadcastReceiver headsetReceiver = new BroadcastReceiver() {
private boolean headsetConnected = false;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Log.v(TAG, "ACTION_HEADSET_PLUG Intent received");
if (intent.hasExtra("state")) {
if (headsetConnected && intent.getIntExtra("state", 0) == 0) {
headsetConnected = false;
headsetSwitch = 0;
// Log.v(TAG, "State = Headset disconnected");
// headsetDisconnected();
} else if (!headsetConnected
&& intent.getIntExtra("state", 0) == 1) {
headsetConnected = true;
headsetSwitch = 1;
// Log.v(TAG, "State = Headset connected");
}
}
switch (headsetSwitch) {
case (0):
headsetDisconnected();
break;
case (1):
break;
}
}
};
private void headsetDisconnected() {
stopMedia();
stopSelf();
}
// --- onDestroy, stop media player and release. Also stop
// phoneStateListener, notification, receivers...---
#Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_NONE);
}
// Cancel the notification
cancelNotification();
// Unregister headsetReceiver
unregisterReceiver(headsetReceiver);
// Unregister seekbar receiver
unregisterReceiver(broadcastReceiver);
// Stop the seekbar handler from sending updates to UI
handler.removeCallbacks(sendUpdatesToUI);
// Service ends, need to tell activity to display "Play" button
resetButtonPlayStopBroadcast();
}
// Send a message to Activity that audio is being prepared and buffering
// started.
private void sendBufferingBroadcast() {
// Log.v(TAG, "BufferStartedSent");
bufferIntent.putExtra("buffering", "1");
sendBroadcast(bufferIntent);
}
// Send a message to Activity that audio is prepared and ready to start
// playing.
private void sendBufferCompleteBroadcast() {
// Log.v(TAG, "BufferCompleteSent");
bufferIntent.putExtra("buffering", "0");
sendBroadcast(bufferIntent);
}
// Send a message to Activity to reset the play button.
private void resetButtonPlayStopBroadcast() {
// Log.v(TAG, "BufferCompleteSent");
bufferIntent.putExtra("buffering", "2");
sendBroadcast(bufferIntent);
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public boolean onInfo(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onSeekComplete(MediaPlayer mp) {
if (!mediaPlayer.isPlaying()) {
playMedia();
Toast.makeText(this, "SeekComplete", Toast.LENGTH_SHORT).show();
}
}
// ---Error processing ---
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Toast.makeText(this,
"MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra,
Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Toast.makeText(this, "MEDIA ERROR SERVER DIED " + extra,
Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Toast.makeText(this, "MEDIA ERROR UNKNOWN " + extra,
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public void onPrepared(MediaPlayer arg0) {
// Send a message to activity to end progress dialogue
sendBufferCompleteBroadcast();
playMedia();
}
#Override
public void onCompletion(MediaPlayer mp) {
// When song ends, need to tell activity to display "Play" button
position += 1;
mp.stop();
mp.release();
Log.v("--", "complete");
// stopMedia();
playMedia();
// stopSelf();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public static void pause() {
mediaPlayer.pause();
}
public static void resume(){
mediaPlayer.start();
}
public static void playMedia() {
if (!mediaPlayer.isPlaying()) {
try {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(songs.get(position).getLink());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
mediaPlayer.setDataSource(songs.get(position).getLink());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void nextSong() {
if (position + 1 == songs.size())
position = 0;
else
position += 1;
playMedia();
}
public static void prevSong() {
if (position - 1 >= 0)
position -= 1;
else
position = songs.size() - 1;
playMedia();
}
// Add for Telephony Manager
public void pauseMedia() {
// Log.v(TAG, "Pause Media");
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
public void stopMedia() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
// Create Notification
private void initNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Tutorial: Music In Service";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.flags = Notification.FLAG_ONGOING_EVENT;
Context context = getApplicationContext();
CharSequence contentTitle = "Music In Service App Tutorial";
CharSequence contentText = "Listen To Music While Performing Other Tasks";
Intent notificationIntent = new Intent(this, Player.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
// Cancel Notification
private void cancelNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(NOTIFICATION_ID);
}
}
My mqtt server does not disconnect while the user kills the app. Still other user can see status is online. Once I close the app I need to disconnect the mqtt server.
1) My first time connection is successful
2) After I close the app the mqtt does not disconnect
3) If anybody sent message it automatically subscribe again
private static BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (LBUtil.isNetworkAvailable(context)) {
if (BuildConfig.DEBUG) {
LBLog.v(TAG, "network is available now");
}
}
}
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
Here start the mqtt service.
#Override
public void onCreate() {
super.onCreate();
LBLog.v(TAG, "start mqtt service");
mApp = (LBApplication) this.getApplicationContext();
mHandler = LBMessageManager.messageHandler;
mServerUri = LBUtil.getMqttBrokerUrl(this);
// register re-subscribe listener
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(LBMessageManager.ACTION_MQTT_SUBSCRIBE);
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
LBLog.v(TAG, "re-subscribe mqtt");
isConnected = false;
if(!mMqttClient.isConnected()){
subscribeMqttTopic();
}
}
};
registerReceiver(receiver, intentFilter);
subscribeMqttTopic();
}
private void subscribeMqttTopic() {
subscriberThread = new Thread(new Runnable() {
public void run() {
do {
try {
mClientId = mApp.getDeviceToken() == null? mApp.getAuthToken():mApp.getDeviceToken();
mTopic = mApp.getSecretKey() + mApp.getUserId();
mWillTopic = mApp.getSecretKey() + mApp.getPartnerId();
if(mServerUri == null){
LBLog.e(TAG, "mServerUri is null");
}
if(mClientId == null){
LBLog.e(TAG, "mClientId is null");
}
if(mMqttClient == null){
mMqttClient = new MqttClient(mServerUri, mClientId, null);
}
Messenger messenger = new Messenger(mHandler);
LBMessageCallback callback = new LBMessageCallback(mApp, messenger);
mMqttClient.setCallback(callback);
final MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(false);
options.setUserName(LBUtil.getMqttServerUsername(mApp));
options.setPassword(LBUtil.getMqttServerPassword(mApp).toCharArray());
// set will message
LBMqttMessage mqttMessage = new LBMqttMessage();
mqttMessage.setFrom(mApp.getUserId());
mqttMessage.setTo(mApp.getPartnerId());
mqttMessage.setType(LBMessageManager.TYPE_STATUS);
mqttMessage.setState(LBMessageManager.STATE_INACTIVE);
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
String jsonString = null;
try {
FilterProvider filters = new SimpleFilterProvider().addFilter("lbMqttMessageFilter", SimpleBeanPropertyFilter.filterOutAllExcept("state", "to", "from"));
jsonString = mapper.writer(filters).writeValueAsString(mqttMessage);
LBLog.v(TAG, "will message=" + jsonString);
} catch (JsonProcessingException e) {
LBLog.e(TAG, "enableMqtt", e);
}
options.setWill(mMqttClient.getTopic(mWillTopic), jsonString.getBytes(), LBMessageMqtt.QOS_1, false);
// connect
mMqttClient.connect(options);
// subscribe
LBLog.v(TAG, "Subscribing mTopic=" + mTopic);
mMqttClient.subscribe(mTopic);
LBLog.v(TAG, "subscribe success");
isConnected = true;
} catch (MqttException e) {
Log.v(TAG, e.toString());
isConnected = false;
try { // wait some time before retry
Thread.sleep(5000);
} catch (InterruptedException e1) {
Log.v(TAG, e1.toString());
}
}
} while (isConnected == false);
}
});
subscriberThread.start();
}
#Override
public void onDestroy() {
super.onDestroy();
LBLog.v(TAG, "destroying mqtt service...");
unregisterReceiver(receiver);
if(mMqttClient != null && mMqttClient.isConnected()){
try {
mMqttClient.disconnect();
} catch (MqttException e) {
LBLog.e(TAG, "onDestroy", e);
}
}
}
}
When exit the application you should manually finish your service. Also there is one call from the broadcast that we don't see its code.
LBUtil.isNetworkAvailable(context)
Make sure that this thing does not starts your service again.
I have a huge problem with the bump API on Android. I setup everything like in the example, the first time I start my activity containing the bump code it works great, now if I go back and start it again it just crash due to a Fatal signal error... It happen right after I call the configure of the bump API.
May I need to not call it again ? But there is nothing to check if it already configured or not.
public class BumpActivity extends Activity {
private IBumpAPI api;
private ProgressDialog mDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bump);
mDialog = ProgressDialog.show(BumpActivity.this, "Preparing bump", "Loading");
bindService(new Intent(IBumpAPI.class.getName()), connection,
Context.BIND_AUTO_CREATE);
IntentFilter filter = new IntentFilter();
filter.addAction(BumpAPIIntents.CHANNEL_CONFIRMED);
filter.addAction(BumpAPIIntents.DATA_RECEIVED);
filter.addAction(BumpAPIIntents.NOT_MATCHED);
filter.addAction(BumpAPIIntents.MATCHED);
filter.addAction(BumpAPIIntents.CONNECTED);
registerReceiver(receiver, filter);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed(){
Intent resultIntent = new Intent();
setResult(Activity.RESULT_CANCELED, resultIntent);
super.onBackPressed();
}
private final ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.i("BumpTest", "onServiceConnected");
api = IBumpAPI.Stub.asInterface(binder);
new Thread() {
public void run() {
try {
api.configure("9b17d663752843a1bfa4cc72d309339e",
"Bump User");
} catch (RemoteException e) {
Log.w("BumpTest", e);
}
}
}.start();
Log.d("Bump Test", "Service connected");
}
#Override
public void onServiceDisconnected(ComponentName className) {
Log.d("Bump Test", "Service disconnected");
}
};
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
try {
if (action.equals(BumpAPIIntents.DATA_RECEIVED)) {
getUserDetailFromBump(new String(
intent.getByteArrayExtra("data")));
} else if (action.equals(BumpAPIIntents.MATCHED)) {
long channelID = intent
.getLongExtra("proposedChannelID", 0);
Log.i("Bump Test",
"Matched with: "
+ api.userIDForChannelID(channelID));
api.confirm(channelID, true);
Toast toast = Toast.makeText(
getApplicationContext(),
"Matched with: "
+ api.userIDForChannelID(channelID),
Toast.LENGTH_SHORT);
toast.show();
} else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED)) {
long channelID = intent.getLongExtra("channelID", 0);
api.send(channelID, CurrentUserManager.getSharedManager()
.getCurrentUser().getUserId().toString().getBytes());
} else if (action.equals(BumpAPIIntents.NOT_MATCHED)) {
Toast toast = Toast.makeText(getApplicationContext(),
"No match", Toast.LENGTH_SHORT);
toast.show();
} else if (action.equals(BumpAPIIntents.CONNECTED)) {
mDialog.dismiss();
api.enableBumping();
}
} catch (RemoteException e) {
}
}
};
public void getUserDetailFromBump(String data) {
Log.i("User Id", data);
LoginRequest login = new LoginRequest(getApplicationContext());
Log.i("Token", login.getArchivedToken());
AsyncHttpClient restRequest = new AsyncHttpClient();
PersistentCookieStore cookie = new PersistentCookieStore(getApplicationContext());
restRequest.setCookieStore(cookie);
RequestParams params = new RequestParams();
params.put("auth_token", login.getArchivedToken());
params.put("user_id", data);
Log.i("Request", "Preparing");
restRequest.get(Constantes.API_URL + "users/show.json", params, new AsyncHttpResponseHandler(){
public void onSuccess(String response) {
Log.i("Reponse", response);
try {
User user = new User(new JSONObject(response));
Log.i("User", user.toString());
//Driver
if (CurrentUserManager.getSharedManager().getCurrentUser().getType() == 1){
CurrentRouteManager.getSharedManager().getCurrentRoute().addPassanger(user);
Intent resultIntent = new Intent(BumpActivity.this, DriverActivity.class);
resultIntent.putExtra("PASSENGER_ADDED", true);
setResult(1, resultIntent);
finish();
}
else{
Intent p = new Intent(BumpActivity.this, RoutePassenger.class);
p.putExtra("driver", user);
startActivity(p);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable e) {
Log.i("Error", e.toString());
}
});
}
public void onStart() {
Log.i("BumpTest", "onStart");
super.onStart();
}
public void onRestart() {
Log.i("BumpTest", "onRestart");
super.onRestart();
}
public void onResume() {
Log.i("BumpTest", "onResume");
super.onResume();
}
public void onPause() {
Log.i("BumpTest", "onPause");
try {
api.disableBumping();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPause();
}
public void onStop() {
Log.i("BumpTest", "onStop");
try {
api.disableBumping();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onStop();
}
public void onDestroy() {
Log.i("BumpTest", "onDestroy");
try {
api.disableBumping();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
unbindService(connection);
unregisterReceiver(receiver);
super.onDestroy();
}
}
I finally resolved it few days ago. As I'm not a JAVA expert I think the bug is located within the Bump library.
If you do api.configure when it is already configured it simply crash. So I ended up making a singleton, ensuring that it is called only once
Here is the code
public class BumpConnection {
protected Context context;
private IBumpAPI api;
private static BumpConnection sharedManager;
public static synchronized BumpConnection getSharedManager(Context context) {
if (sharedManager == null) {
sharedManager = new BumpConnection(context);
}
return sharedManager;
}
private BumpConnection(Context context){
this.context = context;
context.bindService(new Intent(IBumpAPI.class.getName()), connection,
Context.BIND_AUTO_CREATE);
}
public IBumpAPI getApi() {
return api;
}
public void setApi(IBumpAPI api) {
this.api = api;
}
private final ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.i("BumpTest", "onServiceConnected");
api = IBumpAPI.Stub.asInterface(binder);
new Thread() {
public void run() {
try {
api.configure("9b17d663752843a1bfa4cc72d309339e",
"Bump User");
} catch (RemoteException e) {
Log.w("BumpTest", e);
}
}
}.start();
Log.d("Bump Test", "Service connected");
}
#Override
public void onServiceDisconnected(ComponentName className) {
Log.d("Bump Test", "Service disconnected");
}
};
}
Use Latest bump api , available at git hub, read the README.md file carefully.
There is clearly mentioned that by using .aidl file (that is available in src folder) first compile it by using command
android update project -t android-15 -l path_to/bump-api-library -p path_to_your_project/
in your terminal..
If you are a Linux user then set path up to platform-tools then use this command with ./adb .
Then refresh the project , set this Library project as library in your test bump project..
Also replace your bumpapi key that you received via email