I have developed my application using this tutorial:
http://code.tutsplus.com/tutorials/how-to-recognize-user-activity-with-activity-recognition--cms-25851
Even though I request updates every 3 seconds (or for a change, 5 seconds, 10 seconds etc); the timing of the generated values is highly inconsistent. At times it would generate 4 values in 10 minutes! Why is the API being so inconsistent? Also, I'm unable to disconnect the API, even after I call API.disconnect(), I still keep getting values in logcat, which heats up the phone and consumes battery excessively.
Here is the full project: https://github.com/AseedUsmani/MotionAnalyser2
Basic Code:
1) Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_analysing);
mApiClient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mStartButton = (Button) findViewById(R.id.startButton);
mFinishButton = (Button) findViewById(R.id.finishButton);
mStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//resetting counter
for (int j = 0; j < 8; j++) {
mCount[j] = 0;
}
mServiceCount = 0;
mApiClient.connect();
mStartButton.setVisibility(View.INVISIBLE);
mFinishButton.setVisibility(View.VISIBLE);
}
}
mFinishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mApiClient.disconnect();
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Intent intent = new Intent(this, ActivityRecognizedService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mApiClient, 3000, pendingIntent);
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(AnalysingActivity.this, "Connection to Google Services suspended!", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(AnalysingActivity.this, "Connection to Google Services failed!", Toast.LENGTH_LONG).show();
}
}
2) Service:
public class ActivityRecognizedService extends IntentService {
AnalysingActivity mObject = new AnalysingActivity();
int confidence;
public ActivityRecognizedService() {
super("ActivityRecognizedService");
}
public ActivityRecognizedService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
handleDetectedActivities(result.getProbableActivities());
}
}
private void handleDetectedActivities(List<DetectedActivity> probableActivities) {
confidence = mObject.confidence;
mObject.mServiceCount++;
for (DetectedActivity activity : probableActivities) {
switch (activity.getType()) {
case DetectedActivity.IN_VEHICLE: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[0]++;
}
mObject.mActivity[0] = "In Vehicle: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[0]);
Log.e("ActivityRecogition", "In Vehicle: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[0]));
break;
}
case DetectedActivity.ON_BICYCLE: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[1]++;
}
mObject.mActivity[1] = "Cycling: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[1]);
Log.e("ActivityRecogition", "Cycling: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[1]));
break;
}
case DetectedActivity.ON_FOOT: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[2]++;
}
mObject.mActivity[2] = "On Foot: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[2]);
Log.e("ActivityRecogition", "On foot: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[2]));
break;
}
case DetectedActivity.RUNNING: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[3]++;
}
mObject.mActivity[3] = "Running: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[3]);
Log.e("ActivityRecogition", "Running: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[3]));
break;
}
case DetectedActivity.STILL: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[4]++;
}
mObject.mActivity[4] = "Still: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[4]);
Log.e("ActivityRecogition", "Still: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[4]));
break;
}
case DetectedActivity.WALKING: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[5]++;
}
mObject.mActivity[5] = "Walking: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[5]);
Log.e("ActivityRecogition", "Walking: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[5]));
break;
}
case DetectedActivity.TILTING: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[6]++;
}
mObject.mActivity[6] = "Tilting: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[6]);
Log.e("ActivityRecogition", "Tilting: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[6]));
break;
}
case DetectedActivity.UNKNOWN: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[7]++;
}
mObject.mActivity[7] = "Unknown: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[7]);
Log.e("ActivityRecogition", "Unknown: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[7]));
break;
}
}
}
}
}
Per the requestActivityUpdates() documentation:
Activities may be received more frequently than the detectionIntervalMillis parameter if another application has also requested activity updates at a faster rate. It may also receive updates faster when the activity detection service receives a signal that the current activity may change, such as if the device has been still for a long period of time and is then unplugged from a phone charger.
Activities may arrive several seconds after the requested detectionIntervalMillis if the activity detection service requires more samples to make a more accurate prediction.
And
Beginning in API 21, activities may be received less frequently than the detectionIntervalMillis parameter if the device is in power save mode and the screen is off.
Therefore you should not expect calls exactly every 3 seconds, but assume that each call you get is the start of a state change - if you haven't received any callback, it is because nothing has changed.
Also note that the correct call to stop receiving updates is removeActivityUpdates(), passing in the same PendingIntent as you passed into requestActivityUpdates().
Related
I want to make PieChart and when you will press on the your chosen field on PieChart, then you will see Value of Chart (integer 15.. ect.)
I have problem with Toast.maketext when show value of "counter" show value 15.0 insted only 15. I want to have number without .0 at the end.
When I was trying this option below (convert)the app was stopped working:
int x = Integer.parseInt(counter);
int x = Integer.valueOf(counter)
try{ x = Integer.parseInt(counter)}
catch(NumberFormat Exception nfe){}
My code:
pieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
#Override
public void onValueSelected(Entry e, Highlight h) {
Log.d(TAG, "onValueSelected: Value select from chart.");
Log.d(TAG, "onValueSelected: " + e.toString());
Log.d(TAG, "onValueSelected: " + h.toString());
int pos1 = e.toString().indexOf("y: ");
String counter = e.toString().substring(pos1 + 3);
for(int i = 0; i < yData.length; i++){
if(yData[i] == Float.parseFloat(counter)){
pos1 = i;
break;
}
}
String days = xData[pos1];
/*
1.) int x = Integer.parseInt(counter);
2.) int x = Integer.valueOf(counter)
3.)try{ x = Integer.parseInt(counter)}
catch(NumberFormat Exception nfe){}
*/
Toast.makeText(Main2Activity.this, days+ " Day" + "counter" + x, Toast.LENGTH_LONG).show();
//Toast.makeText(Main2Activity.this, days+ " Day" + "counter" + counter, Toast.LENGTH_LONG).show();
//add counter to Toast if you want to show counter
}
#Override
public void onNothingSelected() {
}
});
Thank you for answers :)
Can you try
System.out.print(String.format("%1.0f", counter));
Toast.makeText(Main2Activity.this, days+ " Day" + "counter" + String.format("%1.0f", counter), Toast.LENGTH_LONG).show();
For now I was solving like that:
Log.d(TAG, "onValueSelected: counter num " +counter);
for(int i = 0; i < yData.length; i++){
if(yData[i] == Float.parseFloat(counter)){
pos1 = i;
break;
}
}
String days = xData[pos1];
switch (pos1) {
case 0:
Toast.makeText(Main2Activity.this, days + " Day " + "\n" + "Numbers " +numberBad, Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(Main2Activity.this, days + " Day " + "\n" + "Numbers " +numberGod, Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(Main2Activity.this, days + " Day " + "\n" + "Numbers " +numberNor, Toast.LENGTH_SHORT).show();
break;
default:
break;
}
Hi in the below am not getting any response from server. I am localhost ip address it is not taking.
I am trying to check my ipconfig and using local ip address and not working
I am getting the error while calling an api gateway.
if condition only checking and else condition is not working
I/>>>SchedulerActivity: Sending---http://192.168.0.30retrofit2.Retrofit$1#b357456
light_id:01
intensity:android.support.v7.widget.AppCompatTextView{1fb8ecd7 V.ED.... ........ 30,0-41,28 #7f08010f app:id/txt_bottom61}
cct:8
W/System.err: java.net.ConnectException: Failed to connect to /192.168.0.30:80
W/System.err: at okhttp3.internal.io.RealConnection.connectSocket(RealConnection.java:187)
at okhttp3.internal.io.RealConnection.buildConnection(RealConnection.java:170)
at okhttp3.internal.io.RealConnection.connect(RealConnection.java:111)
at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:187)
at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296)
at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at okhttp3.RealCall.getResponse(RealCall.java:243)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
at okhttp3.RealCall.access$100(RealCall.java:30)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:127)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
private void getCCTAndIntensityValuesForPreset () {
url = "http://192.168.0.30:9000";
Retrofit retrofit = null;
Log.d("123", "retrofit");
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
Log.d("123", "build();");
}
API1 service = retrofit.create(API1.class);
Call<GetScheduler> call = service.getSchedulerData();
Log.i(TAG, "Sending---" + url + service + "\n" + "light_id:" + lightid + "\n" + "intensity:" + dValue1 + "\n" + "cct:" + dayvalue3);
call.enqueue(new Callback<GetScheduler>() {
#Override
public void onResponse(Call<GetScheduler> call, Response<GetScheduler> response) {
if (response != null && response.isSuccessful()) {
String getLightId = response.body().getData().getLight_id();
if (getLightId == "00") {
simpleSwitch.setOn(false);
} else {
simpleSwitch.setOn(true);
}
Toast.makeText(getApplicationContext(), "Light Id" + getLightId, Toast.LENGTH_LONG).show();
//String light_id=response.body()
if(simpleSwitch1.isOn()){
int[] getIntensty = response.body().getData().getCct();
for (int i : getIntensty) {
if(dayvalue1==6){
mIntenisty1.setProgress(getIntensty[0]);
mIntensityTitle1.setText(getIntensty[0] + " %");
}
if(dayvalue2 == 7) {
mIntenisty2.setProgress(getIntensty[1]);
mIntensityTitle2.setText(getIntensty[1] + " %");
}if(dayvalue3==8){
mIntenisty3.setProgress(getIntensty[2]);
mIntensityTitle3.setText(getIntensty[2] + " %");
}
if(dayvalue4==9){
mIntenisty4.setProgress(getIntensty[3]);
mIntensityTitle4.setText(getIntensty[3] + " %");
}
if(dayvalue5==10){
mIntenisty5.setProgress(getIntensty[4]);
mIntensityTitle5.setText(getIntensty[4] + " %");
}
if(dayvalue6==11){
mIntenisty6.setProgress(getIntensty[5]);
mIntensityTitle6.setText(getIntensty[5] + " %");
}
if(dayvalue7==12){
mIntenisty7.setProgress(getIntensty[6]);
mIntensityTitle7.setText(getIntensty[6] + " %");
}
if(dayvalue8==13){
mIntenisty8.setProgress(getIntensty[7]);
mIntensityTitle8.setText(getIntensty[7] + " %");
}
if(dayvalue9==14){
mIntenisty9.setProgress(getIntensty[8]);
mIntensityTitle9.setText(getIntensty[8] + " %");
}
if(dayvalue10==15){
mIntenisty10.setProgress(getIntensty[9]);
mIntensityTitle10.setText(getIntensty[9] + " %");
}
if(dayvalue11==16){
mIntenisty11.setProgress(getIntensty[10]);
mIntensityTitle11.setText(getIntensty[10] + " %");
}
if(dayvalue12==17) {
mIntenisty12.setProgress(getIntensty[11]);
mIntensityTitle12.setText(getIntensty[11] + " %");
}
}
int[] getCCT = response.body().getData().getIntensity();
for (int i : getCCT) {
if (dayvalue1 == 6) {
mCCT1.setProgress(getCCT[0]);
mCCTTitle1.setText(getCCT[0] + " % ");
} if (dayvalue2 == 7) {
mCCT2.setProgress(getCCT[1]);
mCCTTitle2.setText(getCCT[1] + " % ");
} if (dayvalue3 == 8) {
mCCT3.setProgress(getCCT[2]);
mCCTTitle3.setText(getCCT[2] + " % ");
} if (dayvalue4 == 9) {
mCCT4.setProgress(getCCT[3]);
mCCTTitle4.setText(getCCT[3] + " % ");
} if (dayvalue5 == 10) {
mCCT5.setProgress(getCCT[4]);
mCCTTitle5.setText(getCCT[4] + " % ");
} if (dayvalue6 == 11) {
mCCT6.setProgress(getCCT[5]);
mCCTTitle6.setText(getCCT[5] + " % ");
} if (dayvalue7 == 12) {
mCCT7.setProgress(getCCT[6]);
mCCTTitle7.setText(getCCT[6] + " % ");
} if (dayvalue8 == 13) {
mCCT8.setProgress(getCCT[7]);
mCCTTitle8.setText(getCCT[7] + " % ");
} if (dayvalue9 == 14) {
mCCT9.setProgress(getCCT[8]);
mCCTTitle9.setText(getCCT[8] + " % ");
} if (dayvalue10 == 15) {
mCCT10.setProgress(getCCT[9]);
mCCTTitle10.setText(getCCT[9] + " % ");
} if (dayvalue11 == 16) {
mCCT11.setProgress(getCCT[10]);
mCCTTitle11.setText(getCCT[10] + " % ");
} if (dayvalue12 == 17) {
mCCT12.setProgress(getCCT[11]);
mCCTTitle12.setText(getCCT[11] + " % ");
}
}
}
else{
int[] getIntensty = response.body().getData().getCct();
for (int i : getIntensty) {
if(dayvalue1==18){
mIntenisty1.setProgress(getIntensty[0]);
mIntensityTitle1.setText(getIntensty[0] + " %");
}
if(dayvalue2 == 19) {
mIntenisty2.setProgress(getIntensty[1]);
mIntensityTitle2.setText(getIntensty[1] + " %");
}if(dayvalue3==20){
mIntenisty3.setProgress(getIntensty[2]);
mIntensityTitle3.setText(getIntensty[2] + " %");
}
if(dayvalue4==21){
mIntenisty4.setProgress(getIntensty[3]);
mIntensityTitle4.setText(getIntensty[3] + " %");
}
if(dayvalue5==22){
mIntenisty5.setProgress(getIntensty[4]);
mIntensityTitle5.setText(getIntensty[4] + " %");
}
if(dayvalue6==23){
mIntenisty6.setProgress(getIntensty[5]);
mIntensityTitle6.setText(getIntensty[5] + " %");
}
if(dayvalue7==24){
mIntenisty7.setProgress(getIntensty[6]);
mIntensityTitle7.setText(getIntensty[6] + " %");
}
if(dayvalue8==1){
mIntenisty8.setProgress(getIntensty[7]);
mIntensityTitle8.setText(getIntensty[7] + " %");
}
if(dayvalue9==2){
mIntenisty9.setProgress(getIntensty[8]);
mIntensityTitle9.setText(getIntensty[8] + " %");
}
if(dayvalue10==3){
mIntenisty10.setProgress(getIntensty[9]);
mIntensityTitle10.setText(getIntensty[9] + " %");
}
if(dayvalue11==4){
mIntenisty11.setProgress(getIntensty[10]);
mIntensityTitle11.setText(getIntensty[10] + " %");
}
if(dayvalue12==5) {
mIntenisty12.setProgress(getIntensty[11]);
mIntensityTitle12.setText(getIntensty[11] + " %");
}
}
int[] getCCT = response.body().getData().getIntensity();
for (int i : getCCT) {
if (dayvalue1 == 18) {
mCCT1.setProgress(getCCT[0]);
mCCTTitle1.setText(getCCT[0] + " % ");
} if (dayvalue2 == 19) {
mCCT2.setProgress(getCCT[1]);
mCCTTitle2.setText(getCCT[1] + " % ");
} if (dayvalue3 == 20) {
mCCT3.setProgress(getCCT[2]);
mCCTTitle3.setText(getCCT[2] + " % ");
} if (dayvalue4 == 21) {
mCCT4.setProgress(getCCT[3]);
mCCTTitle4.setText(getCCT[3] + " % ");
} if (dayvalue5 == 22) {
mCCT5.setProgress(getCCT[4]);
mCCTTitle5.setText(getCCT[4] + " % ");
} if (dayvalue6 == 23) {
mCCT6.setProgress(getCCT[5]);
mCCTTitle6.setText(getCCT[5] + " % ");
} if (dayvalue7 == 24) {
mCCT7.setProgress(getCCT[6]);
mCCTTitle7.setText(getCCT[6] + " % ");
} if (dayvalue8 == 1) {
mCCT8.setProgress(getCCT[7]);
mCCTTitle8.setText(getCCT[7] + " % ");
} if (dayvalue9 == 2) {
mCCT9.setProgress(getCCT[8]);
mCCTTitle9.setText(getCCT[8] + " % ");
} if (dayvalue10 == 3) {
mCCT10.setProgress(getCCT[9]);
mCCTTitle10.setText(getCCT[9] + " % ");
} if (dayvalue11 == 4) {
mCCT11.setProgress(getCCT[10]);
mCCTTitle11.setText(getCCT[10] + " % ");
} if (dayvalue12 == 5) {
mCCT12.setProgress(getCCT[11]);
mCCTTitle12.setText(getCCT[11] + " % ");
}
}
}
}
}
#Override
public void onFailure(Call<GetScheduler> call, Throwable t) {
t.printStackTrace();
}
});
}
If your server is running on localhost, you need to use the adress http://10.0.2.2 from your android code. Android Emulates a virtual machine, which is different from your regular day to day operating system, thus, it can not access the machine in a regular way. This address was reserved for the android os to communicate with your hosting os through localhost.
I am integrating the AltBeacon API in an existing app. The app shall start actions in the background, when the user enters or leaves a "bluetooth zone".
This functionality should be optional and the user should start and stop the scanning from the settings.
I tryed bind/unbind the BeaconConsumer, but I saw, that in the background the BluetoothLeScanner is keeping scanning! How can I stop the BluetoothLeScanner from scanning? Is this the right way?
Here is the code:
#Override
public void onCreate() {
super.onCreate();
LogManager.setVerboseLoggingEnabled(true);
log.debug("onCreate");
mAllBeaconsRegion = new Region(ALLBEACONS, null, null, null);
mBeaconManager = BeaconManager.getInstanceForApplication(this);
mBackgroundPowerSaver = new BackgroundPowerSaver(this);
mBeaconManager.setBackgroundBetweenScanPeriod(60000L);
mBeaconManager.setBackgroundScanPeriod(2100L);
// wake up the app when a beacon is seen
mRegionBootstrap = new RegionBootstrap(this, mAllBeaconsRegion);
mBeaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
dsGlobal = new DbGlobalsHelper(getApplicationContext());
boolean isBeaconScan = Utils.isBoolean(dsGlobal.getCursorGlobalsByKey(Constants.DB_KEY_BEACON_SCAN));
if(isBeaconScan){
mBeaconManager.bind(this);
}else{
mBeaconManager.unbind(this);
}
}
// Set Regions to monitor at boot/startup
private void setRegionsAtBoot(){
Log.i(TAG, "setRegionsAtBoot");
log.info("setRegionsAtBoot");
SimpleBeaconStore beaconStore = new SimpleBeaconStore(this);
List<SimpleBeacon> beacons = beaconStore.getBeacons();
for (Iterator<SimpleBeacon> iterator = beacons.iterator(); iterator.hasNext();) {
SimpleBeacon simpleBeacon = iterator.next();
List<Identifier> listB = new ArrayList<Identifier>();
StringTokenizer st = new StringTokenizer(simpleBeacon.getBeaconUuid(), "#");
while (st.hasMoreTokens()) {
listB.add(new Identifier(Identifier.parse(st.nextToken())));
}
try {
Log.i(TAG, "setRegionsAtBoot " + simpleBeacon.getId());
log.info("setRegionsAtBoot " + simpleBeacon.getId());
Region region = new Region(simpleBeacon.getId(), listB);
mBeaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
// Start actions
if (region.getUniqueId().equals(ALLBEACONS)){
return;
}
if (beacons.size() > 0) {
for (Beacon beacon: beacons) {
Log.d(TAG, "Beacon "+beacon.toString()+" is about "+beacon.getDistance()+" meters away, with Rssi: "+beacon.getRssi());
log.debug("Beacon " + beacon.toString() + " is about " + beacon.getDistance() + " meters away, with Rssi: " + beacon.getRssi());
datasource = new DbZoneHelper(getApplicationContext());
ZoneEntity ze = datasource.getCursorZoneByName(region.getUniqueId());
if (beacon.getDistance() < ze.getRadius() && !ze.isStatus()) {
//
Log.i(TAG, "Beacon " + beacon.toString() + " Just became less than " + ze.getRadius() + " meters away.");
log.info("*** Beacon " + beacon.toString() + " Just became less than " + ze.getRadius() + " meters away. ***");
String transitionType = getTransitionString(1);
NotificationUtil.sendNotification(getApplicationContext(), transitionType, region.getUniqueId());
worker = new Worker(getApplicationContext());
worker.handleTransition(1, region.getUniqueId(), Constants.BEACON);
}
if (beacon.getDistance() > (ze.getRadius() * EXITMULTIPLICATOR) && ze.isStatus()) {
//
Log.i(TAG, "Beacon "+ beacon.toString()+" Just became over " + ze.getRadius() * EXITMULTIPLICATOR + " meters away.");
log.info("*** Beacon " + beacon.toString() + " Just became over " + ze.getRadius() * EXITMULTIPLICATOR + " meters away. ***");
String transitionType = getTransitionString(2);
NotificationUtil.sendNotification(getApplicationContext(), transitionType, region.getUniqueId());
worker = new Worker(getApplicationContext());
//
worker.handleTransition(2, region.getUniqueId(), Constants.BEACON);
}
}
}
}
#Override
public void didDetermineStateForRegion(int arg0, Region arg1) {
}
#Override
public void didEnterRegion(Region region) {
}
#Override
public void didExitRegion(Region region) {
if (region.getUniqueId().equals(ALLBEACONS)){
return;
}
datasource = new DbZoneHelper(getApplicationContext());
ZoneEntity ze = datasource.getCursorZoneByName(region.getUniqueId());
if (ze.isStatus()) {
//
Log.i(TAG, "Beacon " + region.getUniqueId() + " Just exited region.");
log.info("Beacon " + region.getUniqueId() + " Just exited region.");
String transitionType = getTransitionString(2);
NotificationUtil.sendNotification(getApplicationContext(), transitionType, region.getUniqueId());
worker = new Worker(getApplicationContext());
worker.handleTransition(2, region.getUniqueId(), Constants.BEACON);
}
}
#Override
public void onBeaconServiceConnect() {
Log.d(TAG, "onBeaconServiceConnect.");
log.debug("onBeaconServiceConnect");
setRegionsAtBoot();
mBeaconManager.setRangeNotifier(this);
}
public void bind(){
mBeaconManager.bind(this);
}
public void unbind(){
mBeaconManager.unbind(this);
}
I am also calling the bind/unbind from my settings.
The code shown uses a RegionBootstrap class to continually scan for beacons in the background. This class is essentially designed to never stop scanning for beacons. The RegionBootstrap binds to the scanning service when constructed and effectively never unbinds. The code shown that manually binds and unbinds therefore has no effect.
If you want to start and stop scanning at various times, then don't use the RegionBootstrap class, and instead make your Application or Activity implement BeaconConsumer and bind/unbind as described in the monitoring example code here: http://altbeacon.github.io/android-beacon-library/samples.html
EDIT: New methods have been added to RegionBootstrap to make dynamic region monitoring easier. You can now use: regionBootstrap.disable() to stop scanning entirely, or regionBootstrap.removeRegion(region) to stop looking for a single region.
My application receives messages from GCM.
I have configured a service and a broadcastreceiver correctly. Then, when a message is comming, I show a notification. I have differents notifications for different kind of messages. This runs fine.
Well, now I need to update the notification when a new message is received, such as Whatsapp.
For example, when Whatsapp receives one message from a contact, shows text message, "Hello world!" but when receive another one from same contact, changes the information on notification, showing "Two new messages". If receive message from other contact, notification shows "3 messages on 2 chats" and something like that.
I need to do the same with two type of messages but not all. Then, I need to know which notifications are showing the actionBar and then update ones and no others. I would like to create a bucle for all notifications showed, analyze them and check if there are anyone showed yet of my specific type, previously to create new one.
How can I get info from the notificationManager or StatusActionBar in order to change it? How can I check if the notification showed on Actionbar has the same type of notification comming?
Thanks.
GCMIntentService.java
This service analyze an "extra" value from GCM Message (notificationType). Make a switch case and composes data for show in notification.
Has a method to show the notification. I have put some comments on showNotification method for understad what I need.
public class GCMIntentService extends IntentService {
private String TAG = this.getClass().getSimpleName();
private SQLiteDatabase localDB;
private SharedPreferences localSettings;
public GCMIntentService() {
super(StaticValues.GOOGLE_PROJECT_NUMBER);
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
int gcmNotificationType;
String gcmMess;
long gcmUserIDFrom;
long gcmUserIDTo;
String gcmUserFromCode;
String gcmEventShortDescription;
boolean showNotification = false;
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// Hay notificaciones de varios tipos así que las catalogamos y hacemos cosas diferentes en función del tipo
// Hay que recuperar los settings para saber qué notificaciones se tratan y cuáles no.
if (extras.getString("notificationType") != null) {
gcmNotificationType = Integer.valueOf(extras.getString("notificationType"));
gcmMess = extras.getString("message");
gcmEventShortDescription = extras.getString("eventShortDescription");
gcmUserFromCode = getString(R.string.app_name);
Log.d(TAG, "NotificationType: " + gcmNotificationType);
localSettings = getSharedPreferences(StaticValues.PREFS, 0);
switch (gcmNotificationType) {
case StaticValues.NOTIFICATION_MESSAGE_SINGLE:
Log.d(TAG, "Message received from " + extras.getString("userFromCode"));
localDB = PassObjects.getLocalDB();
gcmUserFromCode = extras.getString("userFromCode");
gcmUserIDFrom = Long.valueOf(extras.getString("userIDFrom"));
gcmUserIDTo = Long.valueOf(extras.getString("userIDTo"));
String inDate;
inDate = FormatValidators.convertTimeStampToString();
GenericMessageMethods.addMessages(gcmUserIDFrom, gcmUserIDTo, gcmMess, inDate, getApplicationContext(), localDB, false);
// Sólo llamo a la cola de broadcast de la pantalla
// si el mensaje es para el perfil en uso
if (gcmUserIDTo == PassObjects.getLOG_INFO_LAST_USER_ID()) {
Intent chatIntent = new Intent("com.example.JourneyApp.journeyActivities.LocalMessagesActivity");
chatIntent.putExtra("userIDFrom",extras.getString("userIDFrom"));
chatIntent.putExtra("userIDTo", extras.getString("userIDTo"));
chatIntent.putExtra("message", extras.getString("message"));
chatIntent.putExtra("messageDate", inDate);
sendBroadcast(chatIntent);
}
if (localSettings.getBoolean("TMP_NOTIFY_MESSAGES_FLAG",true)) {
if (localSettings.getBoolean("NOTIFY_MESSAGES_FLAG",true)) {
showNotification = true;
} else {
Log.d(TAG, "Notifications desactivated: "
+ "MessagesFlag: " + localSettings.getBoolean("NOTIFY_MESSAGES_FLAG",true));
}
} else {
Log.d(TAG, "Notifications TEMPORALLY desactivated. " +
" Processing messages with LocalMessagesActivity running");
}
break;
case StaticValues.NOTIFICATION_MESSAGE_ON_EVENT_ALL_ON_LINE:
Log.d(TAG, "Message received on event " + gcmEventShortDescription + " from " + extras.getString("userFromCode"));
gcmUserFromCode = extras.getString("userFromCode") + " " + getString(R.string.GCM_ON_EVENT) + " " + gcmEventShortDescription;
Intent foroIntent = new Intent("com.example.JourneyApp.journeyActivities.ForoMessagesActivity");
foroIntent.putExtra("userIDFrom",extras.getString("userIDFrom"));
foroIntent.putExtra("eventID", extras.getString("eventID"));
foroIntent.putExtra("message", extras.getString("message"));
foroIntent.putExtra("userFromCode", extras.getString("userFromCode"));
sendBroadcast(foroIntent);
if (localSettings.getBoolean("TMP_NOTIFY_EVENT_MESSAGES_FLAG",true)) {
if (localSettings.getBoolean("NOTIFY_EVENT_MESSAGES_FLAG",true)) {
showNotification = true;
} else {
Log.d(TAG, "Notifications desactivated: "
+ "EventMessagesFlag: " + localSettings.getBoolean("NOTIFY_EVENT_MESSAGES_FLAG",true));
}
} else {
Log.d(TAG, "Notifications TEMPORALLY desactivated: " +
" Processing messages with ForoMessagesActivity running");
}
break;
case StaticValues.NOTIFICATION_NEW_EVENT:
Log.d(TAG, getString(R.string.GCM_new_event_created) + " " + gcmEventShortDescription);
if (localSettings.getInt("NOTIFY_NEW_EVENTS_TYPE_ID",StaticValues.NOTIFICATION_ALWAYS) != StaticValues.NOTIFICATION_NEVER) {
if (localSettings.getInt("NOTIFY_NEW_EVENTS_TYPE_ID",StaticValues.NOTIFICATION_ALWAYS) == StaticValues.NOTIFICATION_ONLY_MY_INTEREST) {
if (PassObjects.getLOG_INFO_LAST_USER_ID() > 0) {
ArrayList<Integer> arrayLikesProfileLogged = PassObjects.getLOG_INFO_USER_LIKES();
ArrayList<Integer> arrayLikesOnEvent = new ArrayList<Integer>();
// Los extras están en String. Lo paso a un String[], lo recorro, parseo a int
// y añado al array. Recorro el del evento y en cuanto encuentro uno coincidente,
// salgo y muestro notificación
String extrasEventLikesString = extras.getString("eventLikes");
Log.d(TAG, "EventLikes: (string) " + extrasEventLikesString);
String[] auxS = extrasEventLikesString.replace(" ", "").split(",");
for (int i = 0; i < auxS.length; i++) {
arrayLikesOnEvent.add(Integer.parseInt(auxS[i]));
}
Log.d(TAG, "EventLikes: (ArrayList<Integer>) " + arrayLikesOnEvent.toString());
for (int x:arrayLikesOnEvent) {
if (arrayLikesProfileLogged.contains(x)) {
gcmMess = getString(R.string.mess_new_event_created);
showNotification = true;
break;
}
}
} else {
Log.d(TAG, "Notification is: " + localSettings.getInt("NOTIFY_NEW_EVENTS_TYPE_ID",StaticValues.NOTIFICATION_ALWAYS) + " but user not logged");
}
} else {
gcmMess = getString(R.string.mess_new_event_created);
showNotification = true;
}
} else {
Log.d(TAG, "Notifications desactivated: "
+ "Notify new events type: " + localSettings.getInt("NOTIFY_NEW_EVENTS_TYPE_ID", StaticValues.NOTIFICATION_ALWAYS) );
}
break;
case StaticValues.NOTIFICATION_NEW_USER:
Log.d(TAG, "New user created: " + extras.getString("userFromCode"));
if (localSettings.getInt("NOTIFY_NEW_USERS_TYPE_ID", StaticValues.NOTIFICATION_ALWAYS) != StaticValues.NOTIFICATION_NEVER) {
if (localSettings.getInt("NOTIFY_NEW_USERS_TYPE_ID", StaticValues.NOTIFICATION_ALWAYS) == StaticValues.NOTIFICATION_ONLY_MY_INTEREST) {
if (PassObjects.getLOG_INFO_LAST_USER_ID() > 0) {
ArrayList<Integer> arrayLikesProfileLogged = PassObjects.getLOG_INFO_USER_LIKES();
ArrayList<Integer> arrayLikesOnUser = new ArrayList<Integer>();
// Los extras están en String. Lo paso a un String[], lo recorro, parseo a int
// y añado al array. Recorro el del evento y en cuanto encuentro uno coincidente,
// salgo y muestro notificación
String extrasUserLikesString = extras.getString("userLikes");
Log.d(TAG, "UserLikes: (string) " + extrasUserLikesString);
String[] auxS = extrasUserLikesString.replace(" ", "").split(",");
for (int i = 0; i < auxS.length; i++) {
arrayLikesOnUser.add(Integer.parseInt(auxS[i]));
}
Log.d(TAG, "UserLikes: (ArrayList<Integer>): " + arrayLikesOnUser.toString());
for (int x:arrayLikesOnUser) {
if (arrayLikesProfileLogged.contains(x)) {
gcmMess = getString(R.string.mess_profile_created_part1);
showNotification = true;
break;
}
}
} else {
Log.d(TAG, "Notification is: " + localSettings.getInt("NOTIFY_NEW_USERS_TYPE_ID", StaticValues.NOTIFICATION_ALWAYS) + " but user not logged");
}
} else {
gcmMess = getString(R.string.mess_profile_created_part1);
showNotification = true;
}
} else {
Log.d(TAG, "Notifications desactivated: "
+ "Notify new uers type: " + localSettings.getInt("NOTIFY_NEW_USERS_TYPE_ID", StaticValues.NOTIFICATION_ALWAYS) );
}
break;
case StaticValues.NOTIFICATION_CHANGE_EVENT:
Log.d(TAG, "Changes on event: " + gcmEventShortDescription);
gcmMess = getString(R.string.GCM_changes_on_event) + " " + gcmEventShortDescription;
showNotification = true;
break;
case StaticValues.NOTIFICATION_LINK_EVENT:
Log.d(TAG, "Linked user from event: " + gcmEventShortDescription);
if (localSettings.getBoolean("NOTIFY_EVENT_LINK_FLAG", true)) {
gcmMess = getString(R.string.mess_linked) + " " + getString(R.string.GCM_ON_EVENT) + " " + gcmEventShortDescription;
showNotification = true;
} else {
Log.d(TAG, "Notifications desactivated: "
+ "Notify link event: " + localSettings.getBoolean("NOTIFY_EVENT_LINK_FLAG", true) );
}
break;
case StaticValues.NOTIFICATION_UNLINK_EVENT:
Log.d(TAG, "Unlinked user from event: " + gcmEventShortDescription);
if (localSettings.getBoolean("NOTIFY_EVENT_UNLINK_FLAG", true)) {
gcmMess = getString(R.string.mess_unlinked) + " " + getString(R.string.GCM_ON_EVENT) + " " + gcmEventShortDescription;
showNotification = true;
} else {
Log.d(TAG, "Notifications desactivated: "
+ "Notify unlink event: " + localSettings.getBoolean("NOTIFY_EVENT_UNLINK_FLAG", true) );
}
break;
case StaticValues.NOTIFICATION_EVENT_CAPACITY_FULL:
Log.d(TAG, "Capacity full on event: " + gcmEventShortDescription);
if (localSettings.getBoolean("NOTIFY_EVENT_CAPACITY_FULL_FLAG", true)) {
gcmMess = getString(R.string.GCM_event_capacity_completed) + " " + gcmEventShortDescription;
showNotification = true;
} else {
Log.d(TAG, "Notifications desactivated: "
+ "Notify event capacity full: " + localSettings.getBoolean("NOTIFY_EVENT_CAPACITY_FULL_FLAG", true));
}
break;
case StaticValues.NOTIFICATION_EVENT_WILL_BEGIN_AT:
Log.d(TAG, "Begin notification on event: " + gcmEventShortDescription);
gcmMess = getString(R.string.GCM_event_will_begin_part_1) + " " + gcmEventShortDescription + " " + getString(R.string.GCM_event_will_begin_part_2);
showNotification = true;
break;
case StaticValues.NOTIFICATION_EVENT_CANCELLED:
Log.d(TAG, "Cancel event: " + gcmEventShortDescription);
gcmMess = getString(R.string.GCM_event_canceled) + " " + gcmEventShortDescription;
showNotification = true;
break;
default:
Log.d(TAG, "Notification not in case");
break;
} //END Switch
if (showNotification) {
showNotification(gcmNotificationType, gcmMess, gcmUserFromCode);
}
} else {
Log.d(TAG, "Cannot find <notificationType> label on extras");
Log.d(TAG, "Extras.size(): " + extras.size() + ", extrasToString " + extras.toString());
}
} else {
Log.d(TAG, "Other GCM message type received");
}
} else {
Log.d(TAG, "Extras are empty");
}
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
private void showNotification(int nType, String mMessage, String mTitle) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// I would like to analyze ActionBar data or NotificationManager data
// Something like...
// for (x:CurrentVisibleNotifications) { // Which will be this object?
// int currentId = x.getId();
// int currentNumber = x.getNumber(); // This is a property of notification
// if (currentId == nType) {
// mMessage = currentNumber++ + " new messages";
// }
// }
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.journey_icon_orange)
.setContentTitle(mTitle)
.setContentText(mMessage)
.setTicker(getString(R.string.app_name))
.setAutoCancel(true)
;
// Intent notIntent = new Intent(this, MainActivity.class);
// PendingIntent contIntent = PendingIntent.getActivity(this, 0, notIntent, 0);
// mBuilder.setContentIntent(contIntent);
mNotificationManager.notify(nType, mBuilder.build());
}
For update a view when your app receive the PushNotification you need LocalBroadCastManager
http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html
In the Service "GCMIntentService", in the method onMessage you need add the nextCode:
Intent intent = new Intent("Reload");
// You can also include some extra data.
intent.putExtra("message", "Reload");
LocalBroadcastManager.getInstance(getApplicationContext())
.sendBroadcast(intent);
Whit this you register a new Broadcasting message.
Now in the class for update you need add the next:
in the onCreate method:
LocalBroadcastManager.getInstance(getApplicationContext())
.registerReceiver(mMessageReceiver,
new IntentFilter("Reload"));
and before you need add next methods:
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
if (message.equalsIgnoreCase("Reload")) {
//Actions...for reload a listView, TextView, etc...
}
}
};
And important add the onDestroy method:
#Override
public void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(getApplicationContext())
.unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
.... PD: Sorry for my English...
i have this gps method:
if (globalconstant.gps) {
globalconstant.mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
globalconstant.mlocManager
.addGpsStatusListener(main.this);
Log.w("TravellerLog :: ", "22");
addGPSListener();
ProgressDialog MyDialog = ProgressDialog.show(
main.this, "Info",
" GPS kapcsolódásra vár... ", true);}
...
/* GPS kapcsolódás figyelő */
public void onGpsStatusChanged(int event) {
// Log.w("TravellerLog :: ", "l1");
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
show_sens = show_sens + "- GPS\n";
sensors.setText(show_sens);
Toast.makeText(getApplicationContext(), "GPS kapcsolódva!",
Toast.LENGTH_SHORT).show();
// Co-ordinates
myChronometer.stop();
myChronometer.setBase(SystemClock.elapsedRealtime());
meres = false;
start_button.setText("START");
break;
case GpsStatus.GPS_EVENT_STARTED:
break;
case GpsStatus.GPS_EVENT_STOPPED:
break;
}
}
the addGPSListener()
// GPS
private void addGPSListener() {
globalconstant.db.setVersion(1);
globalconstant.db.setLocale(Locale.getDefault());
globalconstant.db.setLockingEnabled(true);
final String gps =
"CREATE TABLE IF NOT EXISTS GPS_Values ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, Latitude float(10, 8), Longitude float(10, 8),Accuracy INTEGER,Speed INTEGER,City TEXT,timestamp TIMESTAMP);";
globalconstant.db.execSQL(gps);
Log.d("FESTIVALE :: ", "Frissítési idő: "
+ globalconstant.gps_update_value);
float f = Float.valueOf(globalconstant.gps_update_value.trim())
.floatValue();
float update = f * 1000;
globalconstant.mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
globalconstant.mlocListener = new MyLocationListener();
globalconstant.mlocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, (long) update, 5f,
globalconstant.mlocListener);
// if(Global.getInstance().currentGPSLocation != null){
//
// }
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
float szel = (float) loc.getLatitude();
float hossz = (float) loc.getLongitude();
int horiAcc = (int) (loc.getAccuracy());
// int speed=(int) ((loc.getSpeed()*3600)/1000); //sebesség km/h-ban
int speed = 0;
if (loc.hasSpeed()) {
speed = (int) ((loc.getSpeed() * 3600) / 1000); // sebesség
// km/h-ban
} else {
speed = 0;
}
String test = String.format("%.08f", szel);
String test2 = String.format("%.08f", hossz);
Geocoder geocoder = new Geocoder(main.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(szel, hossz,
1);
city = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
ContentValues gps_values = new ContentValues();
gps_values.put("Latitude", test);
gps_values.put("Longitude", test2);
gps_values.put("Accuracy", horiAcc);
gps_values.put("Speed", speed);
gps_values.put("City", city);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
gps_values.put("timestamp", dateFormat.format(date));
try {
globalconstant.db.beginTransaction();
globalconstant.db.insert("GPS_Values", null, gps_values);
globalconstant.db.setTransactionSuccessful();
} finally {
globalconstant.db.endTransaction();
}
Log.d("FESTIVALE :: ",
"Hely " + test + ", " + test2 + " , " + horiAcc + " , "
+ speed + " , " + city + ","
+ dateFormat.format(date));
// String Text = "My current location is: " + "Latitude = "
// + loc.getLatitude() + "\nLongitude = " + loc.getLongitude();
// Toast.makeText(getApplicationContext(), "Hely" +test + "\n" +
// test2 + "\n" + horiAcc + "\n" +speed + "\n" +city,
// Toast.LENGTH_SHORT)
// .show();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
//
}
public void onStatusChanged(String provider, int status, Bundle extras) {
/* This is called when the GPS status alters */
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
Log.v(tag, "Status Changed: Out of Service");
Toast.makeText(main.this, "Status Changed: Out of Service",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.v(tag, "Status Changed: Temporarily Unavailable");
Toast.makeText(main.this,
"Status Changed: Temporarily Unavailable",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.AVAILABLE:
Log.v(tag, "Status Changed: Available");
Toast.makeText(main.this, "Status Changed: Available",
Toast.LENGTH_SHORT).show();
break;
}
}
}// gps vége
so the question is how can i manage that the gps listener (store in the database the coordinnates...) olny starts when the gps fixed?
thanks for your answers!
You have coded properly, only you need to check certain condition, if the condition gets fulfill then just add lat-lon details to sql, do as follows,
case GpsStatus.GPS_EVENT_FIRST_FIX:
{
...
...
...
new DBThread().start();
}
break;
private class DBThread extends Thread
{
public void run()
{
// Fetch Lat-lon details here and store in sqlite
...
// Remove gps code to save in battery from drain soon
}
}