Here is my simple implementation.
The MapFragment is already initialized. If I do the simulation mode the position indicator is showing but if I switched to the actual TBT navigation it is not showing where I am located.
PositionManager positioningManager;
if(positioningManager == null) {
positioningManager = PositioningManager.getInstance();
positioningManager.addListener(new WeakReference<>(positionChangedListener));
positioningManager.start(PositioningManager.LocationMethod.GPS_NETWORK);
}
positionIndicator = mMap.getPositionIndicator();
positionIndicator.setVisible(true);
positionIndicator.setAccuracyIndicatorVisible(true);
private PositioningManager.OnPositionChangedListener positionChangedListener =
new PositioningManager.OnPositionChangedListener() {
#Override
public void onPositionUpdated(PositioningManager.LocationMethod locationMethod,
GeoPosition geoPosition, boolean b) {
Log.d(TAG, "onPositionUpdated " + locationMethod.name());
Log.d(TAG, "Coordinates " +geoPosition.getCoordinate());
}
#Override
public void onPositionFixChanged(PositioningManager.LocationMethod locationMethod,
PositioningManager.LocationStatus locationStatus) {
Log.d(TAG, "onPositionFixChanged " + locationMethod.name() + " status " + locationStatus.name());
}
};
Related
Okay, so I want to know if it is possible to use AccessibilityService/AccessibilityNodeInfo to turn an android.widget.Switch on/off? Here is my current code and it works to click the text on the screen, but it does not turn a switch on/off.
public void onAccessibilityEvent(AccessibilityEvent event) {
AccessibilityNodeInfo source = event.getSource();
if (source == null) {
return;
}
Log.v(TAG, "Event happened");
processUI(source);
}
And of course, the processUI does everything like compares package, text, etc. and sends it all to clickScreen where it actually clicks the screen.
protected void clickScreen(AccessibilityNodeInfo source, final String text, final String type, final int length)
{
Log.v(TAG, "Clicking: " + source + " / " + text + " / " + type + " / " + length);
if (text == null)
{
Log.v(TAG, "Text is NULL");
return;
}
List<AccessibilityNodeInfo> list = source.findAccessibilityNodeInfosByText(text);
for (AccessibilityNodeInfo node : list) {
Log.i(TAG, "SHOULD BE CLICKING: " + node);
node.performAction(4);
node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
}
list = source
.findAccessibilityNodeInfosByText(text);
for (AccessibilityNodeInfo node : list) {
Log.i(TAG, "MIGHT BE CLICKING: " + node);
node.performAction(4);
node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
}
}
I am trying to make an android app for RFID card reader (i am not using NFC), for this i connect one high frquency RFID card reader through OTG cable and i am using EditText where card number is displaying. it is working fine, but problem is sometime it detects multiple time card number.
1- Any idea how can i resolve this (i cannot put size limit condition because card number length is not fixed)?
2- One more problem when i am using ultra high frequency card reader then card is showing different value, any idea how can i make an android app which supports both frequency card readers.
Rfid continue reading tag its not one time reading so from this repetition you have to manage to your side. Check its reading data or not if yes then ignore.Below the call Where implement Rfid methods and its reading data handle.
public class ReaderListener implements RfidEventListener {
private RfidReader reader;
private ReadInventory eventForm;
//private ItemTransfer eventFormitm;
private final ToneGenerator tg = new ToneGenerator(5, 100);
private boolean isEnabled;
private Map<String, Long> scannedItemsMap = new TreeMap<String, Long>();
public ReaderListener(ReadInventory frm, String make, String macid) throws ReaderConnectionException, LicenseExpiryException, IOException, GeneralSecurityException {
Log.d("Test1", " "+make.toString().trim()+" "+ macid.toString().trim());
reader = RfidFactory.getInstance().getRfidReader(make.toString().trim(), macid.toString().trim(),
PlatformConnector.AndroidConnector.getPlatformName());
Log.d("Test2", " "+reader+" ");
//reader.removeAllListeners();
reader.registerListener(this);
setEnabled(true);
this.eventForm = frm;
}
#Override
public void handleData(String tagid, int arg1, int arg2) {
synchronized (scannedItemsMap) {
if (!scannedItemsMap.containsKey(tagid)) {
System.out.println("got data............ :" + tagid);
scannedItemsMap.put(tagid, System.currentTimeMillis());
if (eventForm != null) {
eventForm.handleData(tagid);
//this.tg.startTone(25);
Log.d("tagid", " " + tagid + " ");
}
/*if (eventFormitm != null) {
eventFormitm.handleData(tagid);
}*/
} else if (scannedItemsMap.containsKey(tagid)) {
scannedItemsMap.put(tagid, System.currentTimeMillis());
}
}
}
#Override
public void handleError(String msg) {
if (eventForm != null) {
eventForm.handleError(msg);
}
}
#Override
public boolean isEnabled() {
return isEnabled;
}
#Override
public void setEnabled(boolean arg0) {
this.isEnabled = arg0;
}
public boolean startScan(int power,int speed) throws ReaderConnectionException {
if (reader != null && !reader.isScanning()) {
reader.setSession(RfidSession.ONE);
reader.setPower(power);
reader.setScanSpeed(speed);
reader.startScan();
}
return true;
}
public void stopScan() throws ReaderConnectionException {
if (reader.isScanning())
reader.stopScan();
}
public boolean isScanning() {
return reader.isScanning();
}
public boolean isConnected() {
return reader.isConnected();
}
public void removeAll() {
scannedItemsMap.clear();
}
public void remove(String tagid) {
scannedItemsMap.remove(tagid);
}
public int getBatteryLevel(){
try {
return reader.getBatteryLevel();
}catch (Exception e){
return 0;
}
}
#Override
public void handleReaderEvent(ReaderEvent arg0) {
// TODO Auto-generated method stub
}
}
Now Handle The data in activity ....
Show in below method.
public void handleData(final String tagid) {
// TODO Auto-generated method stub
try {
final String Code_samplecode = convertHexToString(tagid);
// Log.e("Name", "Itemcode" + Code_samplecode);
if (SampleCode.contains(Code_samplecode)&& !p_SampleCode.contains(Code_samplecode)) {
// Scann items count
tgf.startTone(25);
int ind_val = SampleCode.indexOf(Code_samplecode);
if (ind_val != -1) {
final String SampleNo1 = SampleNo.get(ind_val);
final String StyleNo1 = StyleNo.get(ind_val);
final String SampleCode1 = SampleCode.get(ind_val);
final String StyleCode1 = StyleCode.get(ind_val);
//final String CartStyleCode1 = CartStyleCode.get(ind_val);
// final String CartStyleNo1 = CartStyleNo.get(ind_val);
SampleNo.remove(ind_val);
StyleNo.remove(ind_val);
SampleCode.remove(ind_val);
StyleCode.remove(ind_val);
runOnUiThread(new Runnable() {
#Override
public void run() {
// p_Code.add(Code.get(ind_val));
p_SampleNo.add(SampleNo1);
p_StyleNo.add(StyleNo1);
p_SampleCode.add(SampleCode1);
p_StyleCode.add(StyleCode1);
//Code.remove(ind_val);
// adapter3.notifyDataSetChanged();
// adapter1.notifyDataSetChanged();
total_item.setAdapter(null);
adapter3 = new Adapter_for_Inventoryitem(ReadInventory.this,
StyleNo, SampleNo);
total_item.setAdapter(adapter3);
present_item.setAdapter(null);
adapter1 = new Adapter_for_Inventoryitem(ReadInventory.this,
p_StyleNo, p_SampleNo);
present_item.setAdapter(adapter1);
textvie.setText("Total " + p_SampleNo.size() + " Found Styles");
textvi.setText("Total " + SampleNo.size() + " Available Styles");
List<Inventory> c = db.get_all_data_INVENTARY_Query("SELECT * FROM Inventory_n WHERE SampleCode ='" + SampleCode1 + "'");
if (c.size() > 0) {
db.execute_query("INSERT INTO Inventory_p (Code, SampleNo,StyleNo,SampleCode,StyleCode,CartStyleNo,CartStyleCode) VALUES ('" + c.get(0).getCode() + "' , \"" +
c.get(0).getSampleNo() + "\" , \"" + c.get(0).getStyleNo() + "\" , '" +
c.get(0).getSampleCode() + "' , '" + c.get(0).getStyleCode() + "' , \"" +
c.get(0).getCartStyleNo() + "\" , '" + c.get(0).getCartStyleCode() + "')");
}
db.execute_query("DELETE FROM Inventory_n WHERE SampleCode ='" + SampleCode1 + "'");
}
});
}
} else {
if (!SampleCode.contains(Code_samplecode) && !p_SampleCode.contains(Code_samplecode)
&& !not_fount_items.contains(Code_samplecode)) {
tgn.startTone(20);
scanneditems_unkown = scanneditems_unkown + 1;
runOnUiThread(new Runnable() {
#Override
public void run() {
not_fount_items.add(Code_samplecode);
not_fount_items_txt.setText("Total " + not_fount_items.size() + " Unknown Styles");
}
});
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
scan_counts.setText("Total " + p_SampleNo.size() + " Scanned");
scan_counts_unknown.setText("Total " + scanneditems_unkown + " Unknown");
last_scanned_items.setText("Item : " + Code_samplecode);
}
});
} catch (Exception e) {
e.printStackTrace();
Message message = new Message();
message.what = READEREXCEPTION;
itemDetectedHandler.sendMessage(message);
}
}
You need to Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
//To get the characters (One By one)
event.getDisplayLabel();
}
And use Debounce (I'll recommend using RX Java) if the card numbers are of different length.
What debounce does is, it will wait for a particular amount of time after a keyevent happens, So you can concat the whole string and then use it.
private void initFlightController() {
DJIAircraft aircraft = DJISimulatorApplication.getAircraftInstance();
if (aircraft == null || !aircraft.isConnected()) {
log("initFlightController: aircraft not connected");
showToast("Disconnected");
mFlightController = null;
return;
} else {
log("initFlightController: aircraft CONNECTED");
mFlightController = aircraft.getFlightController();
DJISimulator djiSimulator = mFlightController.getSimulator();
log("initFlightController: djiSimulator has started : "+djiSimulator.hasSimulatorStarted());
djiSimulator.setUpdatedSimulatorStateDataCallback(new DJISimulator.UpdatedSimulatorStateDataCallback() {
#Override
public void onSimulatorDataUpdated(final DJISimulatorStateData djiSimulatorStateData) {
log("onSimulatorDataUpdated: ");
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
String yaw = String.format("%.2f", djiSimulatorStateData.getYaw());
String pitch = String.format("%.2f", djiSimulatorStateData.getPitch());
String roll = String.format("%.2f", djiSimulatorStateData.getRoll());
String positionX = String.format("%.2f", djiSimulatorStateData.getPositionX());
String positionY = String.format("%.2f", djiSimulatorStateData.getPositionY());
String positionZ = String.format("%.2f", djiSimulatorStateData.getPositionZ());
mTextView.setText("Yaw : " + yaw + ", Pitch : " + pitch + ", Roll : " + roll + "\n" + ", PosX : " + positionX +
", PosY : " + positionY +
", PosZ : " + positionZ);
}
});
}
});
}
}
I am testing the sample code given for android in Dji-Developer. Every thing goes fine but the onSimulatorDataUpdated() doesnt get called.
it even prints the log
"initFlightController: djiSimulator has started : true"
I found the solution for the problem. The code doesn't have any problem, the RC has a button at the left front area which has to be set to P mode.
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().
I'm new to android and am using aChartEngine to create a bar chart. I want to capture the x and y values when a user clicks on the chart. I have looked at the demos from aChartEngine and have my chart creating fine. However the onClickListner does not work when I click on the graphy. I have defined the listener in the OnResume method but it doesn't work. Any ideas would be greatly appreciated. Am I missing something here?
Here is my OnResume method which is taken from XYChartBuilder
#Override
protected void onResume() {
super.onResume();
Toast.makeText(Clickable2.this, "In OnResume", Toast.LENGTH_SHORT).show();
if (mChartView == null) {
Toast.makeText(Clickable2.this, "mChartView is null", Toast.LENGTH_SHORT).show();
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getBarChartView(this,mDatasetMethod(titles,x,values),renderer,Type.DEFAULT);
renderer.setClickEnabled(true);
renderer.setSelectableBuffer(100);
//OnClickListener
mChartView.setOnClickListener(new View.OnClickListener() {
// #Override
public void onClick(View v) {
Toast.makeText(Clickable2.this, "ON CLICK", Toast.LENGTH_SHORT).show();
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
double[] xy = mChartView.toRealPoint(0);
if (seriesSelection == null) {
Toast.makeText(Clickable2.this, "No chart element was clicked", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(
Clickable2.this,
"Chart element in series index " + seriesSelection.getSeriesIndex()
+ " data point index " + seriesSelection.getPointIndex() + " was clicked"
+ " closest point value X=" + seriesSelection.getXValue() + ", Y=" + seriesSelection.getValue()
+ " clicked point value X=" + (float) xy[0] + ", Y=" + (float) xy[1], Toast.LENGTH_SHORT).show();
}
}
});
//LongClickListener
mChartView.setOnLongClickListener(new View.OnLongClickListener() {
// #Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
Toast.makeText(Clickable2.this, "ON LONG CLICK", Toast.LENGTH_SHORT).show();
if (seriesSelection == null) {
Toast.makeText(Clickable2.this, "No chart element was long pressed",
Toast.LENGTH_SHORT);
return false; // no chart element was long pressed, so let something
// else handle the event
} else {
Toast.makeText(Clickable2.this, "Chart element in series index "
+ seriesSelection.getSeriesIndex() + " data point index "
+ seriesSelection.getPointIndex() + " was long pressed", Toast.LENGTH_SHORT);
return true; // the element was long pressed - the event has been
// handled
}
}
});
mChartView.addZoomListener(new ZoomListener() {
public void zoomApplied(ZoomEvent e) {
String type = "out";
if (e.isZoomIn()) {
type = "in";
}
System.out.println("Zoom " + type + " rate " + e.getZoomRate());
}
public void zoomReset() {
System.out.println("Reset");
}
}, true, true);
mChartView.addPanListener(new PanListener() {
public void panApplied() {
System.out.println("New X range=[" + renderer.getXAxisMin() + ", " + renderer.getXAxisMax()
+ "], Y range=[" + renderer.getYAxisMax() + ", " + renderer.getYAxisMax() + "]");
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
boolean enabled = mDataset.getSeriesCount() > 0;
} else {
mChartView.repaint();
Toast.makeText(Clickable2.this, "mChartView is NOT null", Toast.LENGTH_SHORT).show();
}
}
Can you check your code for some definition of an object like XYMultipleSeriesRenderer?
Maybe you forgot to set the setClickEnabled method to true?!
Or maybe you should try:
setOnTouchListener
with the method:
public boolean onTouch(View v, MotionEvent event)
It works for me.
Change the value of parameter of setSelectableBuffer method to a bigger number.