Whenever i am running my application I am getting "Service connected" message but after that the BroadcastReceiver are no responding.
what is the problem ?
Can anyone tell me what should i do?
public class BumpTest extends Activity
{
private IBumpAPI api;
private final ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.i("BumpTest", "onServiceConnected");
api = IBumpAPI.Stub.asInterface(binder);
try {
api.configure("8836a26d3545410c9905d90528b2153a",
"ram");//8836a26d3545410c9905d90528b2153a,3826a0e77b284c05960d4513e87c4a88
} catch (RemoteException e) {
Log.w("BumpTest", e);
}
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 {
Log.i("Bump Test", "In Receive " );
if (action.equals(BumpAPIIntents.DATA_RECEIVED)) {
Log.i("Bump Test", "Received data from: " + api.userIDForChannelID(intent.getLongExtra("channelID", 0)));
Log.i("Bump Test", "Data: " + 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);
Log.i("Bump Test", "Confirm sent");
} else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED)) {
long channelID = intent.getLongExtra("channelID", 0);
Log.i("Bump Test", "Channel confirmed with " + api.userIDForChannelID(channelID));
api.send(channelID, "Hello, world!".getBytes());
} else if (action.equals(BumpAPIIntents.NOT_MATCHED)) {
Log.i("Bump Test", "Not matched.");
} else if (action.equals(BumpAPIIntents.CONNECTED)) {
Log.i("Bump Test", "Connected to Bump...");
api.enableBumping();
}else{
System.out.println("inn broadcast rcvr ::: "+api.toString());
}
} catch (RemoteException e) {}
}
};
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bindService(new Intent(IBumpAPI.class.getName()),
connection, Context.BIND_AUTO_CREATE);
Log.i("BumpTest", "boot");
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);
//txtReceived=(TextView)findViewById(R.id.txtReceived);
//bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE);
new BindService().execute();
}
#SuppressLint("NewApi")
class BindService extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE);
return null;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
System.out.println("done");
}
}
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");
super.onPause();
}
public void onStop() {
Log.i("BumpTest", "onStop");
super.onStop();
}
public void onDestroy() {
Log.i("BumpTest", "onDestroy");
super.onDestroy();
try {
unbindService(connection);
unregisterReceiver(receiver);
} catch (Exception e) {
// TODO: handle exception
}
}
}
Related
Actually I want to do speech to text continuously in the background so actually I am using the solution which is given in the below link but i m not getting how can i implement it.
link
I have done this so far but still my service is not running and i am not getting any output
So I think that i have done something wrong in its implementation.Please help me and correct my code in order to run service and get my output
This is my mainactivity.java
public class MainActivity extends AppCompatActivity {
private int mBindFlag ;
private Messenger mServiceMessenger ;
private Button btStartService;
private TextView tvText;
#Override
protected void onStart() {
super.onStart();
Log.d("check", "onStart: ");
bindService(new Intent(getApplicationContext(), MyService.class), mServiceConnection, mBindFlag);
}
#Override
protected void onStop() {
super.onStop();
if (mServiceMessenger != null) {
unbindService(mServiceConnection);
mServiceMessenger = null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent service = new Intent(this, MyService.class);
this.startService(service);
mBindFlag = Context.BIND_ABOVE_CLIENT;
Log.d("check", "onCreate: "+mBindFlag);
btStartService = (Button) findViewById(R.id.btStartService);
tvText = (TextView) findViewById(R.id.tvText);
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {
Manifest.permission.RECORD_AUDIO
};
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
}
public static boolean hasPermissions(Context context, String... permissions) {
if (context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
private final ServiceConnection mServiceConnection = new ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName name, IBinder service)
{
if (DEBUG) {
Log.d("check", "onServiceConnected");} //$NON-NLS-1$
mServiceMessenger = new Messenger(service);
Message msg = new Message();
msg.what = MyService.MSG_RECOGNIZER_START_LISTENING;
try
{
mServiceMessenger.send(msg);
}
catch (RemoteException e)
{
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName name)
{
if (DEBUG) {Log.d("check", "onServiceDisconnected");} //$NON-NLS-1$
mServiceMessenger = null;
}
};
}
This is the code for my background service
public class MyService extends Service
{
protected AudioManager mAudioManager;
protected SpeechRecognizer mSpeechRecognizer;
protected Intent mSpeechRecognizerIntent;
protected final Messenger mServerMessenger = new Messenger(new IncomingHandler(this));
protected boolean mIsListening;
protected volatile boolean mIsCountDownOn;
static final int MSG_RECOGNIZER_START_LISTENING = 1;
static final int MSG_RECOGNIZER_CANCEL = 2;
#Override
public void onCreate()
{
super.onCreate();
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new SpeechRecognitionListener());
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
Log.d("check", "onCreate: "+"service");
}
protected static class IncomingHandler extends Handler
{
private WeakReference<MyService> mtarget;
IncomingHandler(MyService target)
{
mtarget = new WeakReference<MyService>(target);
}
#Override
public void handleMessage(Message msg)
{
final MyService target = mtarget.get();
switch (msg.what)
{
case MSG_RECOGNIZER_START_LISTENING:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
// turn off beep sound
target.mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
if (!target.mIsListening)
{
target.mSpeechRecognizer.startListening(target.mSpeechRecognizerIntent);
target.mIsListening = true;
Log.d("check", "message start listening"); //$NON-NLS-1$
}
break;
case MSG_RECOGNIZER_CANCEL:
target.mSpeechRecognizer.cancel();
target.mIsListening = false;
Log.d("check", "message canceled recognizer"); //$NON-NLS-1$
break;
}
}
}
// Count down timer for Jelly Bean work around
protected CountDownTimer mNoSpeechCountDown = new CountDownTimer(5000, 5000)
{
#Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
}
#Override
public void onFinish()
{
mIsCountDownOn = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_CANCEL);
try
{
mServerMessenger.send(message);
message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
}
};
#Override
public void onDestroy()
{
super.onDestroy();
if (mIsCountDownOn)
{
mNoSpeechCountDown.cancel();
}
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
}
protected class SpeechRecognitionListener implements RecognitionListener
{
private static final String TAG = "check";
#Override
public void onBeginningOfSpeech()
{
// speech input will be processed, so there is no need for count down anymore
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
//Log.d(TAG, "onBeginingOfSpeech"); //$NON-NLS-1$
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
//Log.d(TAG, "onEndOfSpeech"); //$NON-NLS-1$
}
#Override
public void onError(int error)
{
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
mIsListening = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try
{
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
//Log.d(TAG, "error = " + error); //$NON-NLS-1$
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
mIsCountDownOn = true;
mNoSpeechCountDown.start();
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
Log.d("check", "onReadyForSpeech");
}
#Override
public void onResults(Bundle results)
{
Toast.makeText(getApplicationContext(),results.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
#Override
public IBinder onBind(Intent arg0) {
return mServerMessenger.getBinder();
}
}
I got my answer I have not enabled the service from the manifest
I've put together a quick demo of a problem I'm having. When I run the following code, the text is read but there is no beep to prompt for STT and no double beep for the timeout (error 7) but it is running.
public class MainActivity extends AppCompatActivity {
private final String TAG = this.getClass().getSimpleName();
TextToSpeech oTTS;
HashMap<String, String> params = new HashMap<>();
String sTextToSpeak;
String sTextFromSpeech;
SpeechRecognizer sr;
Intent iSRIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AudioManager tmpAm = (AudioManager) getApplicationContext()
.getSystemService(Context.AUDIO_SERVICE);
BroadcastReceiver scoBR = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String TAG = this.getClass().getSimpleName();
Log.i(TAG, "onReceive");
// SCO Connected
if (intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1) ==
AudioManager.SCO_AUDIO_STATE_CONNECTED) {
Log.i(TAG, "SCO Connected");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, "Speaking:" + sTextToSpeak);
// TODO fix deprecation
//noinspection deprecation
oTTS.speak(sTextToSpeak, TextToSpeech.QUEUE_ADD, params);
}
// SCO Disconnected
if (intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1) ==
AudioManager.SCO_AUDIO_STATE_DISCONNECTED) {
Log.i(TAG, "SCO Disconnected");
}
}
};
// Start scoBroadcastReceiver
try {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(scoBR, intentFilter);
Log.i(TAG, "SCOBroadcastReceiver registered");
} catch (Exception e) {
Log.i(TAG, "SCOBroadcastReceiver already registered");
}
oTTS = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
Log.i(TAG, "onInit called");
if (status == TextToSpeech.SUCCESS) {
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "utteranceId");
params.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
String.valueOf(AudioManager.STREAM_VOICE_CALL));
Log.i(TAG, "TTS initialized");
Log.i(TAG, "Start SCO");
tmpAm.startBluetoothSco();
} else {
Log.i(TAG, "Couldn't initialize TTS");
}
}
});
oTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String s) {
Log.i(TAG, "UtteranceProgressListener onStart called");
}
#Override
public void onDone(String s) {
Log.i(TAG, "UtteranceProgressListener onDone called");
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i(TAG, "Calling sr");
sr.startListening(iSRIntent);
}
});
}
#Override
public void onError(String s) {
Log.i(TAG, "UPL onError:" + s);
}
});
sTextToSpeak = "This is a test";
sr = SpeechRecognizer.createSpeechRecognizer(getApplicationContext());
sr.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
Log.i(TAG, "onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.i(TAG, "onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsDb) {
//Log.i(TAG, "rmsDB:"+rmsDb);
}
#Override
public void onBufferReceived(byte[] buffer) {
Log.i(TAG, "onBufferReceived");
}
#Override
public void onEndOfSpeech() {
Log.i(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error) {
Log.i(TAG, "onError:" + error);
tmpAm.stopBluetoothSco();
}
#Override
public void onResults(Bundle results) {
ArrayList data = results.getStringArrayList(
SpeechRecognizer.RESULTS_RECOGNITION);
if (data != null) {
sTextFromSpeech = data.get(0).toString();
} else {
sTextFromSpeech = "";
}
Log.i(TAG, "onResults:" + sTextFromSpeech);
tmpAm.stopBluetoothSco();
}
#Override
public void onPartialResults(Bundle bundle) {
Log.i(TAG, "onPartialResults:" + sTextFromSpeech);
tmpAm.stopBluetoothSco();
}
#Override
public void onEvent(int eventType, Bundle params) {
Log.i(TAG, "onEvent:" + eventType);
}
});
iSRIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
iSRIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
iSRIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
iSRIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak something...");
iSRIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
iSRIntent.putExtra("android.speech.extra.DICTATION_MODE", false);
iSRIntent.putExtra("android.speech.extra.MODE", 1);
iSRIntent.putExtra("android.speech.extra.PREFER_OFFLINE", false);
iSRIntent.putExtra("android.speech.extra.SUGGESTIONS_ENABLED", false);
iSRIntent.putExtra("android.speech.extra.PROFANITY_FILTER", true);
iSRIntent.putExtra("android.speech.extra.AUDIO_ENCODING_REQUESTED", false);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy called");
if (oTTS != null) {
oTTS.stop();
oTTS.shutdown();
}
}
}
I am using AltBeacon Library. I want to scan beacon in 5 min and 1 sec like that. My code not scanning properly on first time and second time scanning properly. please help me?
//this is my fragment class
public class LocationIdFragment extends Fragment {
#Override
public void onStart() {
super.onStart();
Intent intent = new Intent(getActivity(), SimpleService.class);
getActivity().getApplicationContext().startService(intent);
}
#Override
public void onResume() {
super.onResume();
Intent intent = new Intent(getActivity(), SimpleService.class);
getActivity().getApplicationContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
public void onPause() {
super.onPause();
getActivity().getApplicationContext().unbindService(mConnection);
mBound = false;
}
#Override
public void onStop() {
super.onStop();
Intent intent = new Intent(getActivity(), SimpleService.class);
getActivity().getApplicationContext().stopService(intent);
}
}
//this is my service class
public class SimpleService extends Service implements BeaconConsumer {
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onCreate() {
super.onCreate();
beaconManager = BeaconManager.getInstanceForApplication(getBaseContext());
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
beaconManager.setForegroundScanPeriod(1000);//this is not scanning properly
beaconManager.setBackgroundScanPeriod(1000);
beaconManager.setForegroundBetweenScanPeriod(301000);
beaconManager.setBackgroundBetweenScanPeriod(301000);
beaconManager.bind(SimpleService.this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
try {
// Unbind scan beacon progress
if (beaconManager != null) {
beaconManager.unbind(SimpleService.this);
beaconManager.stopRangingBeaconsInRegion(new Region("sBeacon", null, null, null));
}
} catch (Exception e) {
e.printStackTrace();
}
super.onDestroy();
}
#Override
public void onBeaconServiceConnect() {
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
if (beacons.size() > 0) {
beacon = beacons.iterator().next();
getMajor = beacon.getId2().toString();//here i'm getting data
getMinor = beacon.getId3().toString();
beaconID = getMajor + "-" + getMinor;
DateFormat df = new SimpleDateFormat("dd-MM-yyyy/hh:mm:ss.mmm");// i'm getting different time
String sDate = df.format(Calendar.getInstance().getTime());
String[] sDateTime = sDate.split("/");
}
}
});
try {
beaconManager.startRangingBeaconsInRegion(new Region("sBeacon", null, null, null));
Log.i(TAG, "*** startRangingBeaconsInRegion ***");
Logger.info(" LocationIdFragment : Start Ranging BeaconsInRegion ");
} catch (RemoteException e) {
Log.i(TAG, "RemoteException: " + e);
}
}
}
Service class:
private IBinder mBinder ;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
}
#Override
public void onDestroy() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("service","started");
new Connect().execute("");
return Service.START_STICKY;
}
private class Connect extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
ConnectionConfiguration connConfig = new ConnectionConfiguration(
HOST, PORT, SERVICE);
final XMPPConnection connection = new XMPPConnection(connConfig);
Thread t= new Thread(new Runnable() {
#Override
public void run() {
try {
connection.connect();
// SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.login(USERNAME, PASSWORD);
Log.i("NetWorkConnection",
"Logged in as " + connection.getUser());
System.out.println(connection);
setConnection(connection);
} catch (XMPPException ex) {
Log.e("NetWorkConnection", "Failed to log in as "
+ USERNAME);
Log.e("NetWorkConnection", ex.toString());
setConnection(null);
}
}});
t.start();
return null;
}
}
public void setConnection(XMPPConnection connection) {
NetworkConnection.connection = connection;
}
public class MyBinder extends Binder
{
NetworkConnection getService() {
return NetworkConnection.this;
}
}
public XMPPConnection getconnection()
{
if (connection != null) {
Log.d("NetworkConnection","connection send");
return connection;
}
else
{
Log.d("NetworkConnection","connection null");
return null;
}
}
}
Activity Class:
private NetworkConnection service;
XMPPConnection connection=NetworkConnection.connection;
Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_in);
next=(Button)findViewById(R.id.bRetry);
if(!isMyServiceRunning())
{
Intent i=new Intent(this,NetworkConnection.class);
startService(i);
}
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
System.out.println(connection);
if(connection!=null)
{
Intent i = new Intent (getApplicationContext(),UserIndex.class);
startActivity(i);
}else{
Intent i = new Intent(SignIn.this,SignIn.class);
startActivity(i);
}
}
});
}
#Override
protected void onResume() {
bindService(new Intent(this, NetworkConnection.class), mConnection,
Context.BIND_AUTO_CREATE);
super.onResume();
}
#Override
protected void onPause() {
unbindService(mConnection);
super.onPause();
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
service = ((NetworkConnection.MyBinder) binder).getService();
Log.d("Service","Connected");
System.out.println("service connection methoddd");
connection=service.getconnection();
}
public void onServiceDisconnected(ComponentName className) {
connection=null;
service = null;
}
};
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (NetworkConnection.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
I am creating a chat application using XMPP and asmack, So i used service. But the problem is that when i start the service onServiceConnected method never execute.That is why when i retrieve the connection object from service it always give null value. I have not much idea about it . please guide me.
I have found a working demo and successfully worked with that.but the problem is i have implemented it with minimum version 10 where StrictPolicy is importable.now i want min sdk version 1.6 or above to work with Bump.
I have also seen that AsysncTask for BindService can be used but not worked for me.suggest something what wrong i am doing
int sdkVersion = android.os.Build.VERSION.SDK_INT;
if(sdkVersion>9)
{
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}catch (Exception e) {
// TODO: handle exception
}
}
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);
filter.addAction(BumpAPIIntents.DISCONNECTED);
filter.addAction(BumpAPIIntents.BUMPED);
this.registerReceiver(receiver, filter);
//txtReceived=(TextView)findViewById(R.id.txtReceived);
//bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE);
new BindService().execute();
}
class BindService extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
System.out.println("done");
}
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
} */
#Override
public void onDestroy()
{
super.onDestroy();
try {
unbindService(connection);
unregisterReceiver(receiver);
} catch (Exception e) {
// TODO: handle exception
}
}
private final ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder binder)
{
Log.i("Bump", "onServiceConnected");
api = IBumpAPI.Stub.asInterface(binder);
try
{
api.configure("KEY_HERE", "Some text..");
}
catch (RemoteException e)
{
Log.i("Bump", "api.configured failed");
}
}
#Override
public void onServiceDisconnected(ComponentName className)
{
Log.i("Bump", "onServiceDisconnected");
}
};
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)) {
Log.i("Bump", "DATA_RECEIVED");
Log.i("Bump", "Received data from: " + api.userIDForChannelID(intent.getLongExtra("channelID", 0)));
Log.i("Bump", "Data: " + new String(intent.getByteArrayExtra("data")));
//AlertDialog.Builder diaBuilder=
} else if (action.equals(BumpAPIIntents.MATCHED)) {
Log.i("Bump", "MATCHED");
api.confirm(intent.getLongExtra("proposedChannelID", 0), true);
} else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED)) {
Log.i("Bump", "CHANNEL_CONFIRMED");
api.send(intent.getLongExtra("channelID", 0), (StaticData.strUserId + ","+ StaticData.strHomeName + ","+ StaticData.strUserImgUrl).getBytes());
} else if (action.equals(BumpAPIIntents.CONNECTED)) {
Log.i("Bump", "CONNECTED");
api.enableBumping();
}
else if (action.equals(BumpAPIIntents.DISCONNECTED)) {
Log.i("Bump", "DISCONNECTED");
} else if (action.equals(BumpAPIIntents.BUMPED)) {
Log.i("Bump", "BUMPED");
}
else if (action.equals(BumpAPIIntents.NOT_MATCHED)) {
Log.i("Bump", "NOT_MATCHED");
}
else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED_EXTRA_CHANNEL_ID)) {
Log.i("Bump", "CHANNEL_CONFIRMED_EXTRA_CHANNEL_ID");
}
else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED_EXTRA_CHANNEL_ID)) {
Log.i("Bump", "CHANNEL_CONFIRMED_EXTRA_CHANNEL_ID");
}
} catch (RemoteException e) {}
}
};
the working demo i have used above is docs.google.com/open?id=0B8f-N2PC8e0vU0gxRm1jaG51RGM