I would like to get back results in a variable of type String. The contents of what the user tells his smartphone via Google now that is: "OK google claptrap " I would like to do this so I could get back 'claptrap'. I have already searched but have been unsuccessful. I found how to return my selectable application in Google now like, for example write a note in my app but in this case the person has to say " OK google note at me claptrap " so that I can get back claptrap. It is not proceeding well … I am pretty sure that it is possible because the app "commandr" already makes it for commands as "turn on the torch".
Excuse my bad english.
Thank you in advance Good evening :D
i have create a AccessibilityService for get command google now but i should touch editText for receive the command. Help me please
public class NotificationService extends AccessibilityService {
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
System.out.println("******onAccessibilityEvent*******");
if(event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED || event.getEventType() == AccessibilityEvent.TYPE_WINDOWS_CHANGED) {
System.out.println(" NAME : " + event.getClassName());
System.out.println(" NAME PCK : " + event.getPackageName());
System.out.println(" SOURCE : " + event.getSource());
System.out.println(" TEXT : " + event.getText());
}
}
private String RecupCommandGoogle(AccessibilityEvent mEvent, AccessibilityNodeInfo mSource) {
if (mSource != null & mEvent.getClassName().equals("android.view.View")) {
return String.valueOf(mSource.performAction(AccessibilityNodeInfo.ACTION_SELECT));
}
return null;
}
#Override
protected void onServiceConnected() {
System.out.println("onServiceConnected");
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.eventTypes = AccessibilityEvent.TYPE_WINDOWS_CHANGED | AccessibilityEvent.TYPE_VIEW_FOCUSED ;
info.packageNames = new String[] {"com.google.android.launcher" , "com.google.android.googlequicksearchbox"};
info.feedbackType = AccessibilityEvent.TYPES_ALL_MASK;
info.notificationTimeout = 100;
setServiceInfo(info);
}
#Override
public void onInterrupt() {
System.out.println("onInterrupt");
}
}
Related
A short and simple question someone hopefully has an awnser to:
How can I navigate with the Here Android SDK Premium through road elemts that have the attributes DIR_NO_CARS, NO_THROUGH_TRAFFIC, DIR_NO_TRUCKS in the TRUCK transport mode? Like I am a special car and I can drive on these roads.
My code looks like the following:
public class Scratch extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AndroidXMapFragment mapFragment = (AndroidXMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapfragment);
boolean success = com.here.android.mpa.common.MapSettings.setIsolatedDiskCacheRootPath(
getApplicationContext().getExternalFilesDir(null) + File.separator + ".here-maps",
"MainActivity");
System.out.println(success);
mapFragment.init(new OnEngineInitListener() {
#Override
public void onEngineInitializationCompleted(
OnEngineInitListener.Error error) {
if (error == OnEngineInitListener.Error.NONE) {
// now the map is ready to be used
Map map = mapFragment.getMap();
for (String sheme : map.getMapSchemes()) {
Log.d("Custom", sheme);
}
map.setMapScheme("pedestrian.day");
map.setMapDisplayLanguage(Locale.GERMANY);
//Show current position marker
PositioningManager.getInstance().start(PositioningManager.LocationMethod.GPS_NETWORK);
mapFragment.getPositionIndicator().setVisible(true);
//Routing
GeoCoordinate start = new GeoCoordinate(50.992189, 10.999966);
GeoCoordinate target = new GeoCoordinate(51.001224, 10.990920);
//Start - End marker for routing
MapLabeledMarker markerStart = new MapLabeledMarker(start)
.setLabelText(map.getMapDisplayLanguage(), "Start")
.setIcon(IconCategory.ALL);
markerStart.setZIndex(12);
map.addMapObject(markerStart);
MapLabeledMarker markerTarget = new MapLabeledMarker(target)
.setLabelText(map.getMapDisplayLanguage(), "End")
.setIcon(IconCategory.ALL);
markerTarget.setZIndex(12);
map.addMapObject(markerTarget);
CoreRouter router = new CoreRouter();
router.setDynamicPenalty(NewPenaltyForStreetArea(
router.getDynamicPenalty(),
new GeoCoordinate(51.001137, 10.989901),
new GeoCoordinate(50.992582, 10.999338),
map.getMapDisplayLanguage(),
"Im Geströdig",
DrivingDirection.DIR_BOTH,
70
));
RouteOptions routeOptions = new RouteOptions();
routeOptions.setTransportMode(RouteOptions.TransportMode.TRUCK);
routeOptions.setRouteType(RouteOptions.Type.FASTEST);
routeOptions.setCarpoolAllowed(false);
routeOptions.setCarShuttleTrainsAllowed(false);
routeOptions.setDirtRoadsAllowed(true);
routeOptions.setTruckLength(6.590f);
routeOptions.setTruckWidth(2.150f);
routeOptions.setTruckHeight(2.150f);
routeOptions.setTruckTrailersCount(0);
routeOptions.setTruckDifficultTurnsAllowed(true);
routeOptions.setRouteCount(2);
RoutePlan routePlan = new RoutePlan();
routePlan.setRouteOptions(routeOptions);
routePlan.addWaypoint(new RouteWaypoint(start));
routePlan.addWaypoint(new RouteWaypoint(target));
class RouteListener implements CoreRouter.Listener {
// Method defined in Listener
public void onProgress(int percentage) {
// Display a message indicating calculation progress
Log.d("Custom", percentage + "");
}
// Method defined in Listener
#Override
public void onCalculateRouteFinished(List<RouteResult> routeResult, RoutingError error) {
// If the route was calculated successfully
if (error == RoutingError.NONE) {
// Render the route on the map
Log.d("Custom", routeResult.size() + " Routes calculated");
for (RouteResult result : routeResult) {
MapRoute mapRoute = new MapRoute(result.getRoute());
mapRoute.setColor(Color.argb(100, 201, 42, 42));
mapRoute.setZIndex(10);
if (routeResult.indexOf(result) == 0) {
//Best route
mapRoute.setColor(Color.argb(255, 201, 42, 42));
mapRoute.setZIndex(11);
}
map.addMapObject(mapRoute);
}
}
else {
// Display a message indicating route calculation failure
}
}
}
router.calculateRoute(routePlan, new RouteListener());
} else {
System.out.println("ERROR: Cannot initialize AndroidXMapFragment");
System.out.println(error);
}
}
});
}
private DynamicPenalty NewPenaltyForStreetArea(DynamicPenalty dynamicPenalty, GeoCoordinate cord1, GeoCoordinate cord2, String marcCode, String streetName, DrivingDirection drivingDirection, int speed){
List<GeoCoordinate> penaltyArea = new ArrayList<>();
penaltyArea.add(cord1);
penaltyArea.add(cord2);
List<RoadElement> roadElements = RoadElement.getRoadElements(GeoBoundingBox.getBoundingBoxContainingGeoCoordinates(penaltyArea), marcCode);
for (int i = 0; i < roadElements.size(); i++) {
//Log.d("Custom", roadElements.get(i).getRoadName());
if (!roadElements.get(i).getRoadName().equals(streetName)){
roadElements.remove(i);
i--;
}
else
Log.d("Custom", roadElements.get(i).getAttributes().toString());
}
Log.d("Custom", "Set penalty for " + roadElements.size() + " road elements - " + streetName);
for (RoadElement road : roadElements) {
dynamicPenalty.addRoadPenalty(road, drivingDirection, speed);
}
return dynamicPenalty;
}
}
And this is what I get
But this is what I need
So I want to say the navigation API that the road "Im Geströdig" is accessible for my car.
Road Element Attributes I need to change somehow:
[DIR_NO_CARS, DIRT_ROAD, NO_THROUGH_TRAFFIC, DIR_NO_TRUCKS]
The solution to the use case is not trivial. The functionality of updating Road Element attributes is available via the HERE Custom Route API, where you would need to upload an overlay with a shape, that matches the road you want to modify. The attributes which can be updated are also limited. ("VEHICLE_TYPES":"49" indicates road is open for Cars, Truck, Pedestrian)
GET http://cre.api.here.com/2/overlays/upload.json
?map_name=OVERLAYBLOCKROAD
&overlay_spec=[{"op":"override","shape":[[50.10765,8.68774],[50.10914,8.68771]],"layer":"LINK_ATTRIBUTE_FCN","data":{"VEHICLE_TYPES":"49"}}]
&storage=readonly
&app_id={YOUR_APP_ID}
&app_code={YOUR_APP_CODE}
Make sure to use the same AppId, Appcode as being used with HERE Premium Mobile SDK.
Now this overlay can be used in HERE Premium Mobile SDK with FTCRRouter (still Beta feature)
FTCRRouter ftcrRoute = new FTCRRouter();
FTCRRouter.RequestParameters parmaters =new
FTCRRouter.RequestParameters(routePlan,"OVERLAYBLOCKROAD",true);
ftcrRoute.calculateRoute(parmaters, new FTCRRouter.Listener() {
#Override
public void onCalculateRouteFinished(List<FTCRRoute> list,
FTCRRouter.ErrorResponse errorResponse) {
if (errorResponse.getErrorCode() == RoutingError.NONE) {
List<GeoCoordinate> shape = list.get(0).getGeometry();
MapPolyline polyline = new MapPolyline();
polyline.setGeoPolyline(new GeoPolygon(shape));
polyline.setLineWidth(10);
m_map.addMapObject(polyline);
}else{
// Error
}
}
});
As the FTCRRouter is still in Beta, there are some limitation like Dynamic Penanlity is not supported and also the FTCRRouter always prefers to take the roads available in HERE Map data and uses the Roads from the overlay if necessary.
Please review following code and let me know what I need to change for showing remote video. Audio is playing fine. Working Latest library of Webrtc.In onAddStream method I have get Videotrack size of 1 but is not render in remoteVideoTrack addSink method.
private PeerConnection createPeerConnection(PeerConnectionFactory peerConnectionFactory, boolean isLocal) {
//
PeerConnection.RTCConfiguration rtcConfig = new PeerConnection.RTCConfiguration(getServerList());
//
PeerConnection.Observer pcObserver = new CustomPeerConnectionObserver("localPeerCreation") {
#Override
public void onIceCandidate(IceCandidate iceCandidate) {
super.onIceCandidate(iceCandidate);
//SignallingClient.getInstance().sendICECandidate(iceCandidate);
if (iceCandidate.serverUrl.length() > 1)
SignallingClient.getInstance().sendICECandidate(iceCandidate);
}
#Override
public void onAddStream(MediaStream mediaStream) {
super.onAddStream(mediaStream);
Log.e("mytagVFrame", "Video Frame is OUt == " + mediaStream.videoTracks.size());
VideoTrack remoteVideoTrack = mediaStream.videoTracks.get(0);
remoteVideoTrack.setEnabled(true);
ProxyVideoSink videoSink = new ProxyVideoSink();
videoSink.setTarget(mRemoteSurfaceViewRenderer);
remoteVideoTrack.addSink(videoSink);
}
};
return peerConnectionFactory.createPeerConnection(rtcConfig, pcObserver);
//
}
I had the same problem. I discovered I was calling EglBase.create(); in two different places
i have implemented a webview in my android app and trying to highlight or to mark element when user click in the layout.
The webview is initialized as following :
myWebView.getSettings().setJavaScriptEnabled(true);
//myWebView.getSettings().setGeolocationEnabled(true);
//myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.setWebViewClient(new WebViewController());
Trying to mark the element which is clicked by user for example like in this screenshot :
Selection with dot
I'm getting all the page divs via jsoup :
doc = Jsoup.connect(url).get();
final Elements alldivs = doc.select("div");
ArrayList<String> list = new ArrayList<String>();
for (org.jsoup.nodes.Element e : alldivs) {
if (!e.id().equals(""))
list.add(e.id());
}
But how to mark the selection as the photo above, and after that select marked content from div id.
How can make some thing like this ?
I'm using this javascript into webview to hightlight the selection but how to get the clicked element programmatically like : id of selected div or other values
public class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript: "
+ "Object.prototype.each = function (fn, bind) {\n" +
" console.log(bind);\n" +
" for (var i = 0; i < this.length; i++) {\n" +
" if (i in this) {\n" +
" fn.call(bind, this[i], i, this);\n" +
" }\n" +
" }\n" +
" };\n" +
"\n" +
" var _addListener = document.addEventListener || document.attachEvent,\n" +
" _eventClick = window.addEventListener ? 'click' : 'onclick';\n" +
"\n" +
" var elements = document.getElementsByTagName(\"div\");\n" +
"\n" +
" elements.each(function (el) {\n" +
" _addListener.call(el, _eventClick, function () {\n" +
// todo process the clicked div element
" el.style.cssText = \"border-color: black;border-style: dashed;\"\n" +
" }, false);\n" +
" })");
}
}
If I understand correctly, you want to get some information from the HTML component into the native side.
According to this answer, it is not possible to pass arbitrary objects to Java, but at least you can pass the HTML code of the clicked node and then parse it natively.
This code based on yours does exactly that.
MainActivity.java: I guess this is pretty self-explanatory. The only thing I did different from you is to get the Javascript code from a separate file, so it's easier to maintain.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView myWebView = findViewById(R.id.webView);
final WebSettings settings = myWebView.getSettings();
settings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
final String injectedJs = "javascript:(function(){" + injectedJs() + "})()";
myWebView.loadUrl(injectedJs);
}
});
myWebView.addJavascriptInterface(
new Object() {
#JavascriptInterface
public void onClick(String param) {
Toast.makeText(MainActivity.this, param, Toast.LENGTH_LONG).show();
}
},
"appHost"
);
myWebView.loadUrl("https://google.com");
}
// Javascript code to inject on the Web page
private String injectedJs() {
BufferedReader stream = null;
StringBuilder jsBuilder = new StringBuilder();
try {
stream = new BufferedReader(new InputStreamReader(getAssets().open("js.js")));
String line;
while ((line = stream.readLine()) != null) {
jsBuilder.append(line.trim());
}
return jsBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}
}
js.js: The base of this part is your code. Keep in mind that since injectedJs() removes all line markers, every statement needs to finish, including comments, hence the /*...*/ instead of //
/* Keep track of the last clicked element so we can un-highlight it */
var lastSelectedItem = null;
var showHighlighted = function(/* HTML element */view, /*boolean */highlighted) {
if (view) {
view.style.cssText = highlighted? 'border-color: black;border-style: dashed;' : '';
}
};
/* This new method, _addEventListener and _eventClick are the same as yours */
Object.prototype.each = function (fn, bind) {
for (var i = 0; i < this.length; i++) {
if (i in this) {
fn.call(bind, this[i], i, this);
}
}
};
var _addListener = document.addEventListener || document.attachEvent,
_eventClick = window.addEventListener ? 'click' : 'onclick';
/* I changed the element selection criteria, but you can change it back easily.
I am adding event listeners all the leaf elements in the DOM. */
var elements = document.body.getElementsByTagName('*');
elements.each(function (el) {
if (el.children.length == 0) {
_addListener.call(el, _eventClick, function () {
/* First, deal with the previously selected item*/
showHighlighted(lastSelectedItem, false);
if (lastSelectedItem !== null) {
appHost.onClick(lastSelectedItem.outerHTML);
}
/* Update the selected item reference */
lastSelectedItem = el;
/* Finally, deal with the previously selected item*/
showHighlighted(lastSelectedItem, true);
appHost.onClick(el.outerHTML);
}, false);
}
});
consider the web view as a view of a web page. You need to configure the element inside that web view to send a request that would fire an intent in your android application, which is possible, but it would not work for multiple users unless you know the user in that web view and authenticate the users... the point is , it is very complicated if you want to send that request from web to the logical part of your app. Even if you can do it, it is not optimal and i discourage it.
On the other hand, what you can do if you insist on using web views is to complete the rest of your logical operations on the web view. Don't go back from the web view to the app java logic.
Normally web views are used to show something rather than to make actions on the app. (the action might be used on the same web view)
I hope you do get , I've tried to explain as much as possible.
So in my app I have the following functionality for receiving bitcoins
kit.wallet().addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
#Override
public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
txtLog.append("-----> coins resceived: " + tx.getHashAsString() + "\n");
txtLog.append("received: " + tx.getValue(wallet) + "\n");
Futures.addCallback(tx.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
#Override
public void onSuccess(TransactionConfidence result) {
txtLog.append("\nSuccess! Recieved: " + tx.getValue(wallet) + "\n");
//Find address of sender here
}
#Override
public void onFailure(Throwable t) {
throw new RuntimeException(t);
}
});
}
});
This works great, OnSuccess triggers properly once a transaction is confirmed and added to my wallet. txtLog is just a textArea in my java frame which displays some text output for me. What I need to do now is find the address of the sender at this point, can i do this with the Transaction object tx? Any help would be appreciated.
Found the solution! Unfortunately it uses a depreciated method. I just added the following in the appropriate spot.
String address = "";
for (TransactionInput txin : tx.getInputs()){
address = txin.getFromAddress().toString();
}
I am implementing Facebook friends invite in my android app and I need to get to how many friends user sent app request so that I can award him some points.
What I have done so far is as below
WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(this,
sessiob, params)).setOnCompleteListener(
new OnCompleteListener() {
#Override
public void onComplete(Bundle values,FacebookException error) {
if (error != null) {
} else {
final String requestId = values.getString("request");
final String[] requestArr1 = values.getStringArray("to");
if (requestId != null) {
Log.e("RequestId1",requestId + "\n" + values.toString());
else {
Toast.makeText(Login.this,"Request cancelled", Toast.LENGTH_SHORT).show();
}
}
}
}).build();
And the Bundle value I am getting is Bundle[{to[0]=808411111111111,to[1]=151584774222222, request=879734911111111}]
While my above code final String requestId = values.getString("request"); working fine however values.getStringArray("to"); giving me Null.
I want to know value "to" inside the Bundle is a StringArray or not and if yes then what's wrong in my extraction process.
Check out this example you will find your all answers
Simple facebook