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);
}
}
}
Related
I am using altbeacon for android and i cant't detect my beacon. I have tried https://github.com/AltBeacon/android-beacon-library-reference sample code also but can't detect beacon. Here is my code:
public class BeaconApplication extends Application implements BootstrapNotifier {
private Region region;
private RegionBootstrap regionBootstrap;
private BeaconManager beaconManager;
#Override
public void onCreate() {
super.onCreate();
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
beaconManager.setBackgroundScanPeriod(5000);
beaconManager.setBackgroundBetweenScanPeriod(10000);
region = new Region("backgroundRegion",
Identifier.parse("EBEFD083-70A2-47C8-9837-E7B5634DF524"), null, null);
regionBootstrap = new RegionBootstrap(this, region);
Log.i("selfBeacon", "Bootstrap created");
}
#Override
public void didEnterRegion(Region region) {
Log.i("selfBeacon", "Bootstrap didEnterRegion");
regionBootstrap.disable();
Intent intent = new Intent(this, SelfBeaconService.class);
if (Build.VERSION.SDK_INT >= 26) {
startForegroundService(intent);
} else {
startService(intent);
}
Log.i("selfBeacon", "Service start commanded");
}
#Override
public void didExitRegion(Region region) {
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
public void resumeScanning () {
beaconManager.setBackgroundScanPeriod(5000);
beaconManager.setBackgroundBetweenScanPeriod(10000);
regionBootstrap = new RegionBootstrap(this, region);
Log.i("selfBeacon", "scanning resumed");
}
}
public class SelfBeaconService extends Service implements BeaconConsumer {
private BeaconManager beaconManager;
private Region region;
private int noBeaconDetectedCount = 0;
#Override
public void onCreate() {
super.onCreate();
Log.i("selfBeaconService", "onCreate");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("selfBeaconService", "onStartCommand");
broadcastSystemLog("Beacon Service onCreate triggered.");
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.setEnableScheduledScanJobs(false); //Stop scanning
beaconManager.setForegroundScanPeriod(2000);
beaconManager.setForegroundBetweenScanPeriod(2000);
beaconManager.bind(this);
region = new Region("foreground region",
Identifier.parse("EBEFD083-70A2-47C8-9837-E7B5634DF524"), null, null);
startForeground();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onBeaconServiceConnect() {
Log.i("selfBeaconService", "onBeaconServiceConnect");
broadcastSystemLog("onBeaconServiceConnect triggered.");
beaconManager.addRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> collection, Region region) {
if (collection.size() > 0) {
noBeaconDetectedCount = 0;
double closestDistance = -1;
for (Beacon each : collection) {
if (closestDistance == -1) {
closestDistance = each.getDistance();
} else if (each.getDistance() < closestDistance) {
closestDistance = each.getDistance();
}
}
Log.i("selfBeaconService", "didRangeBeaconsInRegion, the closest beacon is about " +
closestDistance + " meters away.");
broadcastToActivity("The closest beacon is about " +
closestDistance + " meters away.");
} else {
noBeaconDetectedCount++;
broadcastToActivity("No beacon has been detected for " + noBeaconDetectedCount + " times");
if (noBeaconDetectedCount > 10) { //10*(2000ms+2000ms) = 40 seconds
stopForeground(true);
terminate();
}
}
}
});
try {
beaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
Log.i("selfBeacon", "onDestroy");
broadcastSystemLog("BeaconService onDestroy triggered.");
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void broadcastToActivity (String message) {
Intent intent = new Intent();
intent.setAction("beaconBroadcast");
intent.putExtra("beaconService", message);
sendBroadcast(intent);
}
private void broadcastSystemLog (String message) {
Intent intent = new Intent();
intent.setAction("beaconBroadcast");
intent.putExtra("beaconServiceLog", message);
sendBroadcast(intent);
}
private void startForeground () {
NotificationCompat.Builder notificationBuilder = null;
Notification notification = null;
if (Build.VERSION.SDK_INT >= 26) {
notificationBuilder = new NotificationCompat.Builder(this, "rangingService")
.setContentTitle("Active Scanning")
.setContentText("App is scanning for nearby beacons");
notification = notificationBuilder.build();
} else {
notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Active Scanning")
.setContentText("App is scanning for nearby beacons");
notification = notificationBuilder.build();
}
startForeground(1234, notification);
}
private void terminate () {
try {
beaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
beaconManager.removeAllRangeNotifiers();
beaconManager.unbind(this);
beaconManager.setEnableScheduledScanJobs(true);
((BeaconApplication)getApplication()).resumeScanning();
stopSelf();
Log.i("selfBeaconService", "service stopped");
broadcastSystemLog("BeaconSevice stopped.");
}
}
A few things to check:
Ensure you have added code to dynamically request location permission at runtime. See here for how to do that.
After adding the above, make sure this permission has been properly obtained. Go to. Settings->Apps->{your app name}->Permissions to see
Make sure Bluetooth and Location are enabled on your phone.
If you have checked all of the above and it still does not work, try an off the shelf beacon detector like BeaconScope. If it does not detect, there may be a problem with either your phone hardware or your beacon hardware.
I am using this code for ranging and monitoring in Altbeacon
class Appclass extends Application implements BootstrapNotifier {
private RegionBootstrap regionBootstrap;
private BackgroundPowerSaver backgroundPowerSaver;
private boolean haveDetectedBeaconsSinceBoot = false;
public static Region region1;
private static boolean activityVisible;
public static Appclass instances;
public static BeaconManager beaconManager;
public void onCreate() {
super.onCreate();
instances = this;beaconManager=org.altbeacon.beacon.BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser()
.setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
beaconManager.setForegroundScanPeriod(1100l);
beaconManager.setForegroundBetweenScanPeriod(0l);
beaconManager.setAndroidLScanningDisabled(true);
beaconManager.setBackgroundBetweenScanPeriod(01);
beaconManager.setBackgroundScanPeriod(1100l);
try {
beaconManager.updateScanPeriods();
} catch (Exception e) {
}
Log.d("", "setting up background monitoring for beacons and power saving");
// wake up the app when a beacon is seen
region1 = new Region("backgroundRegion",
null, null, null);
regionBootstrap = new RegionBootstrap(this, region1);
backgroundPowerSaver = new BackgroundPowerSaver(this);
}
#Override
public void didEnterRegion(Region region) {
Log.d("ABC", "Enter");
Log.d("ABC value", region.getId2() + " " + region.getId3());
try { Intent i = new Intent(getApplicationContext(), AbcService.class);
startService(i);
} catch (Exception e) {
}
}
#Override
public void didExitRegion(Region region) {
Log.d("ABC", "exit");
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
and then in my AbcService class code is:
class AbcService extends Service implements BeaconConsumer, MonitorNotifier, RangeNotifier {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Appclass.beaconManager.bind(this);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
} catch (Exception e) {
}
return START_STICKY;
}
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> collection, Region region) {
Log.d("ABC", "range");
}
#Override
public void onBeaconServiceConnect() {
Appclass.beaconManager.setMonitorNotifier(this);
Appclass.beaconManager.setRangeNotifier(this);
}
#Override
public void didEnterRegion(Region region) {
try {
Log.d("ABC", "didEnterRegion");
Log.d("ABC", "" + region.getId2() + region.getId3());
Appclass.beaconManager.startRangingBeaconsInRegion(Appclass.region1);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void didExitRegion(Region region) {
try {
Log.d("ABC", "didExitRegion");
Appclass.beaconManager.stopRangingBeaconsInRegion(Appclass.region1);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
}
now issue are getting that the didEnterRegion method of Application class calling every time when we enter in beacon range but the didEnterRegion method of AbcService class not calling some time and also not start ranging. what is the issue in my code?
A few tips:
Start ranging the same time as you start monitoring. There is no reason to wait for an entered region callback or to stop ranging when you exit the region.
Add logging to didDetermineStateFirRegion. This method gets called when a beacon appears after app startup even if the device was already in region from when it was previously running. didEnterRegion only gets called if beacons matching the region actually disappear for 15+ seconds and then reappear.
I have been refering to Android Speech Recognition as a service on Android 4.1 & 4.2 post to try and implement speech recognition in a service.
I guess I have got it right. On running in my device I am getting "Ready for Speech" toast message which I have declared inside onReadyForSpeech() function.
According to Hoan Nguyen the person who gave the ans for the above post, we can start speaking as soon as onReadyForSpeech() function is called.
My problem is I don't know how to get the speech which we are speaking and convert it to text and where to do it.
Does any one know how to do it? I know its a very lame question to ask but its my first time working with speech recognition. So please bear with me.
Any help on this is very much appreciated. Thanks in advance :)
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());
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
//Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
Log.d("onCreate","Entered");
}
protected static class IncomingHandler extends Handler
{
private WeakReference<MyService> mtarget;
IncomingHandler(MyService target)
{
mtarget = new WeakReference<MyService>(target);
Log.d("IncomingHandler","Entered");
}
#Override
public void handleMessage(Message msg)
{
Log.d("handleMessage","Entered");
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("TAG", "message start listening");
//$NON-NLS-1$
}
break;
case MSG_RECOGNIZER_CANCEL:
target.mSpeechRecognizer.cancel();
target.mIsListening = false;
Log.d("TAG", "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
Log.d("onTick","Entered");
}
#Override
public void onFinish()
{
Log.d("onFinish","Entered");
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 int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
try
{
Message msg = new Message();
msg.what = MSG_RECOGNIZER_START_LISTENING;
mServerMessenger.send(msg);
}
catch (RemoteException e)
{
Log.d("msg",""+e);
}
return START_NOT_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy()
{
super.onDestroy();
if (mIsCountDownOn)
{
mNoSpeechCountDown.cancel();
}
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
Log.d("onDestroy","Entered");
}
protected class SpeechRecognitionListener implements RecognitionListener
{
private static final String TAG = "Sppech---->";
#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$
Log.d("onBeginningOfSpeech","Entered");
}
#Override
public void onBufferReceived(byte[] buffer)
{
String sTest = "";
Log.d("onBufferReceived","Entered");
}
#Override
public void onEndOfSpeech()
{
//Log.d(TAG, "onEndOfSpeech"); //$NON-NLS-1$
Log.d("onEndOfSpeech","Entered");
}
#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$
Log.d("onError","Entered");
}
#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("TAG", "onReadyForSpeech");
Toast.makeText(getApplicationContext(), "Ready for Speech", Toast.LENGTH_SHORT).show();
Log.d("onReadyForSpeech","Entered");//$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//Log.d(TAG, "onResults"); //$NON-NLS-1$
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You get it in onResult(Bundle result), which you can then get what the user speak into an ArrayList
ArrayList<String> matches = result.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
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
}
}
}
I am trying to make an Activity run a certain service.
I followed the tutorial here but adapted to my code, and I can't make it work, because when I am invoking the service after starting and binding it to the activity, my Interface (IMyRemoteCallsLoggingService) object does not seem to have the connection properly created.
I have been trying to make this work for several days but I can't seem to get rid of a NullPointException.
Not sure if I made myself clear, in which case here's the code:
public class MtprojectActivity extends Activity {
[...]
private boolean started = false;
private RemoteSmsLoggingServiceConnection SmsLoggingConn = null;
private RemoteCallsLoggingServiceConnection CallsLoggingConn = null;
private IMyRemoteCallsLoggingService callsLoggingService;
private IMyRemoteSmsLoggingService smsLoggingService;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrievePreferences();
Button prefBtn = (Button) findViewById(R.id.prefsBtn);
prefBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Explicit intent to call the preferences
Intent preferencesActivity = new Intent(getBaseContext(),
Preferences.class);
startActivity(preferencesActivity);
}
});
}
private void retrievePreferences() {
// Get the xml/preferences.xml preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
callsCheckbox = prefs.getBoolean("callsLogChk", false);
smsCheckbox = prefs.getBoolean("smsLogChk", false);
locationCheckbox = prefs.getBoolean("locationLogChk", false);
if (callsCheckbox) {
startCallsService();
bindCallsService();
try {
invokeCallsService();
} catch (RemoteException e) {
e.printStackTrace();
}
} else {
}
private void startCallsService() {
if (started) {
Toast.makeText(MtprojectActivity.this, "Service already started",
Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent();
i.setClassName("app.mtproject", "app.mtproject.CallsLoggingService");
startService(i);
started = true;
updateCallsServiceStatus();
Log.d(getClass().getSimpleName(), "startService()");
}
}
private void bindCallsService() {
if (CallsLoggingConn == null) {
CallsLoggingConn = new RemoteCallsLoggingServiceConnection();
Intent i = new Intent();
i.setClassName("app.mtproject", "app.mtproject.CallsLoggingService");
bindService(i, CallsLoggingConn, Context.BIND_AUTO_CREATE);
updateCallsServiceStatus();
Log.d(getClass().getSimpleName(), "bindService()");
} else {
Toast.makeText(MtprojectActivity.this,
"Cannot bind - service already bound", Toast.LENGTH_SHORT)
.show();
}
}
private void invokeCallsService() throws RemoteException {
if (CallsLoggingConn == null) {
Toast.makeText(MtprojectActivity.this,
"Cannot invoke - service not bound", Toast.LENGTH_SHORT)
.show();
} else {
callsLoggingService.dumpCallsLog();
TextView t = (TextView) findViewById(R.id.notApplicable);
t.setText("It worked!");
Log.d(getClass().getSimpleName(), "invokeService()");
}
}
class RemoteCallsLoggingServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className,
IBinder boundService) {
callsLoggingService = IMyRemoteCallsLoggingService.Stub
.asInterface((IBinder) boundService);
Log.d(getClass().getSimpleName(), "onServiceConnected()");
}
public void onServiceDisconnected(ComponentName className) {
callsLoggingService = null;
updateCallsServiceStatus();
Log.d(getClass().getSimpleName(), "onServiceDisconnected");
}
};
I get a NullPointerException right on callsLoggingService.dumpCallsLog() in the invokeCallsService() method, and I'm not sure what's the problem!
Here's the code of the service:
public class CallsLoggingService extends Service {
String date, duration, type;
private Handler serviceHandler;
private Task myTask = new Task();
#Override
public IBinder onBind(Intent arg0) {
Log.d(getClass().getSimpleName(), "onBind()");
return myRemoteCallsServiceStub;
}
private IMyRemoteCallsLoggingService.Stub myRemoteCallsServiceStub = new IMyRemoteCallsLoggingService.Stub() {
public void dumpCallsLog() throws RemoteException {
CallsLoggingService.this.dumpCallsLog();
}
};
#Override
public void onCreate() {
super.onCreate();
Log.d(getClass().getSimpleName(), "onCreate()");
}
#Override
public void onDestroy() {
super.onDestroy();
serviceHandler.removeCallbacks(myTask);
serviceHandler = null;
Log.d(getClass().getSimpleName(), "onDestroy()");
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
serviceHandler = new Handler();
serviceHandler.postDelayed(myTask, 10L);
Log.d(getClass().getSimpleName(), "onStart()");
}
class Task implements Runnable {
public void run() {
try {
myRemoteCallsServiceStub.dumpCallsLog();
} catch (RemoteException e) {
e.printStackTrace();
}
serviceHandler.postDelayed(this, 86400000L);
Log.i(getClass().getSimpleName(), "Calling the dumpCallsLog");
}
}
private synchronized void dumpCallsLog() {
ContentResolver cr = getContentResolver();
String columns[] = new String[] { CallLog.Calls.DATE,
CallLog.Calls.DURATION, CallLog.Calls.TYPE };
Uri mContacts = CallLog.Calls.CONTENT_URI;
Cursor c = cr.query(mContacts, columns, // Which columns to return
null, // WHERE clause; which rows to return(all rows)
null, // WHERE clause selection arguments (none)
CallLog.Calls.DEFAULT_SORT_ORDER // Order-by clause
// (ascending
// by name)
);
if (c.moveToFirst()) {
do {
// Get the field values
date = c.getString(c.getColumnIndex(CallLog.Calls.DATE));
duration = c
.getString(c.getColumnIndex(CallLog.Calls.DURATION));
type = c.getString(c.getColumnIndex(CallLog.Calls.TYPE));
} while (c.moveToNext());
}
}
}
Thanks a lot everybody for the help!
bindService() is asynchronous. You cannot use callsLoggingService until onServiceConnected() is called.