How to detect physical key click in a android wearable? - android

I am using sony smartwatch 3 and it has a power button which I want to control or say manipulate.
I have already tried using :
onKeyDown()
onKeyUp()
onKeyLongPress()
but with no success it doesn't even detect the press of key.
I have also tried using dispatchkeyevent(keyevent event) and shouldOverrideKeyEvent(keyevent event)but again no success.
Please guide.

You need to initialize and connect with GoogleApiClient. Once you clicks the button you have to get list of nodes and send a message to them. The last step is to read this message fron phone part of app, this can be done by registering proper WearableListenerService. Please see the sample code below.
Wearable App:
public class WearableButtonActivity extends Activity {
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wearable_button_activity);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
}
public void onButtonClicked(View target) {
if (mGoogleApiClient == null)
return;
final PendingResult<NodeApi.GetConnectedNodesResult> nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient);
nodes.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult result) {
final List<Node> nodes = result.getNodes();
if (nodes != null) {
for (int i=0; i<nodes.size(); i++) {
final Node node = nodes.get(i);
// You can just send a message
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), "/MESSAGE", null);
// or you may want to also check check for a result:
// final PendingResult<SendMessageResult> pendingSendMessageResult = Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), "/MESSAGE", null);
// pendingSendMessageResult.setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
// public void onResult(SendMessageResult sendMessageResult) {
// if (sendMessageResult.getStatus().getStatusCode()==WearableStatusCodes.SUCCESS) {
// // do something is successed
// }
// }
// });
}
}
}
});
}
}
Listener:
findViewById(R.id.button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onButtonClicked(v);
}
});
Phone App:
public class DataLayerListenerService extends WearableListenerService {
#Override
public void onMessageReceived(MessageEvent messageEvent) {
super.onMessageReceived(messageEvent);
if("/MESSAGE".equals(messageEvent.getPath())) {
// launch some Activity or do anything you like
}
}
}

Related

ARCore – Is there any event for asset changed position/orientation?

I am new to creating AR app using ARCore and Sceneform for Android (Java). I am building a multiplayer app using cloud anchors where two or more people can interact on one or more asset. When the asset changes it's position, how to get the event to broadcast to other connected users?
Here's my code:
private AppAnchorState appAnchorState = AppAnchorState.NONE;
private SnackbarHelper snackbarHelper = new SnackbarHelper();
private StorageManager storageManager;
private Socket mSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/******************* Here **************************/
// connect to socket
mSocket = new ArSync().onCreate();
mSocket.connect();
// listen for change event
mSocket.on("modelChanged", new Emitter.Listener() {
#Override
public void call(final Object... args) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//TODO: call the application to load reslove by number
//textView.setText("Current ID is :" +
args[0].toString());
Log.d("Triggered", args[0].toString());
onResolveOkPressed(args[0].toString());
}
});
}
});
fragment = (CustomArFragment) getSupportFragmentManager().findFragmentById(R.id.sceneform_fragment);
//To add
fragment.getPlaneDiscoveryController().hide();
fragment.getArSceneView().getScene().setOnUpdateListener(this::onUpdateFrame);
Button clearButton = findViewById(R.id.clear_button);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setCloudAnchor(null);
}
});
Button resolveButton = findViewById(R.id.resolve_button);
resolveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cloudAnchor != null){
snackbarHelper.showMessageWithDismiss(getParent(), "Please clear Anchor");
return;
}
ResolveDialogFragment dialog = new ResolveDialogFragment();
dialog.setOkListener(MainActivity.this::onResolveOkPressed);
dialog.show(getSupportFragmentManager(), "Resolve");
}
});
fragment.setOnTapArPlaneListener(
(HitResult hitResult, Plane plane, MotionEvent motionEvent) -> {
if (plane.getType() != Plane.Type.HORIZONTAL_UPWARD_FACING ||
appAnchorState != AppAnchorState.NONE){
return;
}
Anchor newAnchor = fragment.getArSceneView().getSession().hostCloudAnchor(hitResult.createAnchor());
setCloudAnchor(newAnchor);
appAnchorState = AppAnchorState.HOSTING;
snackbarHelper.showMessage(this, "Now hosting anchor...");
placeObject(fragment, cloudAnchor, Uri.parse("Fox.sfb"));
}
);
storageManager = new StorageManager(this);
}
/*.....
.......
.......
*/
I have written a separate Socket.io server in NodeJS to broadcast the Short hand GUID to other connected nodes to download and resolve the asset at launch of the app. It works fine when I am rendering the asset for the first time. But I am not sure how to handle when one person moves that asset. I want it to render it other connected devices. I could not find any event to asset changed so that I could attach my code to it.

TelephonyManager.requestNetworkScan - Android P Preview

Has anyone tried this API?
I'm developing a privileged system app to scan the network.
For some reason I get error 2 'Wrong parameters' when I try using it.
Granted the app MODIFY_PHONE_STATE permission, and still get the error
Here's an extract:
public class ScannerActivity extends Activity implements View.OnClickListener {
private final int PHONE_STATE_REQUEST = 1;
private Button scanButton;
private TextView resultsTextView;
private class RadioCallback extends TelephonyScanManager.NetworkScanCallback {
private List<CellInfo> mCellInfoResults;
private int mScanError;
#Override
public void onResults(List<CellInfo> cellInfoResults) {
mCellInfoResults = cellInfoResults;
ScannerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
for (CellInfo cellInfo:mCellInfoResults) {
resultsTextView.append(" " + cellInfo.toString() + " ");
}
}
});
}
#Override
public void onError(int error) {
mScanError = error;
ScannerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
resultsTextView.append(" Error: " + mScanError);
}
});
}
#Override
public void onComplete() {
ScannerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
resultsTextView.append(" Scan Completed! ");
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner);
scanButton = (Button) findViewById(R.id.scan_button);
scanButton.setOnClickListener(this);
resultsTextView = (TextView) findViewById(R.id.results_text_view);
}
public void onClick(View view) {
NetworkScanRequest networkScanRequest;
RadioAccessSpecifier radioAccessSpecifiers[];
int bands[];
ArrayList<String> PLMNIds = new ArrayList<String>(Arrays.asList("42501"));
TelephonyManager telephonyManager = (TelephonyManager) getApplicationContext()
.getSystemService(Context.TELEPHONY_SERVICE);
bands[0] = AccessNetworkConstants.UtranBand.BAND_1;
radioAccessSpecifiers = new RadioAccessSpecifier[1];
radioAccessSpecifiers[0] = new RadioAccessSpecifier(
AccessNetworkConstants.AccessNetworkType.UTRAN,
bands,
null);
networkScanRequest = new NetworkScanRequest(
NetworkScanRequest.SCAN_TYPE_ONE_SHOT,
radioAccessSpecifiers,
0,
60,
false,
0,
PLMNIds);
telephonyManager.requestNetworkScan(networkScanRequest, AsyncTask.SERIAL_EXECUTOR,new RadioCallback());
}
}
Does anyone has an idea what parameters did i pass wrong?
I first thought that it might be LTE / 3G issue, but I get the same results both for UTRAN & EUTRAN.
I also ruled out SIM issue - the same error happens with 2 different SIMS, both successfully scanning the network form settings app for example.
OK, figured it out - for anyone who may come across this issue -
searchPeriodicity & incrementalResultsPeriodicity cannot be 0, despite the documentation,
and irrelevance of these parameters for one shot scan.

receiving error when building an android project with Neura

I'm working with neura sdk in order to detect current data of a user(where he/she is, where were they 10 min ago etc).
I want to login to their api, and authenticate my user, however - when i call NeuraApiClient.authenticate(...) nothing happens.
I followed neura documentations, but still - nothing happens.
Here's my code :
public class MainActivity extends AppCompatActivity {
private ArrayList<Permission> mPermissions;
private AuthenticationRequest mAuthenticateRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Builder builder = new Builder(this);
NeuraApiClient neuraApiClient = builder.build();
neuraApiClient.setAppUid(getResources().getString(R.string.app_uid));
neuraApiClient.setAppSecret(getResources().getString(R.string.app_secret));
neuraApiClient.connect();
fetchPermissions(neuraApiClient);
neuraApiClient.authenticate(100, mAuthenticateRequest);
}
private void fetchPermissions(final NeuraApiClient client) {
client.getAppPermissions(new GetPermissionsRequestCallbacks() {
#Override
public void onSuccess(final List<Permission> permissions) throws RemoteException {
runOnUiThread(new Runnable() {
#Override
public void run() {
mPermissions = new ArrayList<>(permissions);
mAuthenticateRequest = new AuthenticationRequest();
mAuthenticateRequest.setAppId(client.getAppUid());
mAuthenticateRequest.setAppSecret(client.getAppSecret());
mAuthenticateRequest.setPermissions(mPermissions);
}
});
}
#Override
public void onFailure(Bundle resultData, int errorCode) throws RemoteException {
}
#Override
public IBinder asBinder() {
return null;
}
});
}
}
getAppPermissions is an asynchronous call, and the data is fetched on GetPermissionsRequestCallbacks.
in GetPermissionsRequestCallbacks you're initiating mAuthenticateRequest which is in use of authenticate method.
Which means you have to wait untill onSuccess of GetPermissionsRequestCallbacks is called, and only then you can call
neuraApiClient.authenticate(100, mAuthenticateRequest);
Basically, if you don't wait for mAuthenticateRequest to be fetched, you authenticate with mAuthenticateRequest = null, and neuraApiClient.authenticate(..) fails.
You can do something like this : call authenticate when the results are received -
private void fetchPermissions(final NeuraApiClient client) {
client.getAppPermissions(new GetPermissionsRequestCallbacks() {
#Override
public void onSuccess(final List<Permission> permissions) throws RemoteException {
runOnUiThread(new Runnable() {
#Override
public void run() {
mPermissions = new ArrayList<>(permissions);
mAuthenticateRequest = new AuthenticationRequest();
mAuthenticateRequest.setAppId(client.getAppUid());
mAuthenticateRequest.setAppSecret(client.getAppSecret());
mAuthenticateRequest.setPermissions(mPermissions);
client.authenticate(100, mAuthenticateRequest);
}
});
}
...
});
}

Where to place function to fetch data from server when waiting for location data

I'm building an application that has to get data from the server according to the latitude and longitude get by Google Play Services Location API. I'm not able to figure out where to place the functions to get location and to fetch data from server. I'm going to explain me better. When the application start I have to get the last known location and I have seen that this is possible through
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CurrentGeolocation currentGeolocation = CurrentGeolocation.get(getActivity());
}
#Override
public void onStart() {
super.onStart();
mCurrentGeolocation.connectGoogleApiClient();
}
CurrentGeolocation
public static CurrentGeolocation get(Context appContext) {
if (sCurrentGeolocation == null) {
sCurrentGeolocation = new CurrentGeolocation(appContext.getApplicationContext());
}
return sCurrentGeolocation;
}
private CurrentGeolocation(Context appContext) {
mAppContext = appContext;
mRequestingLocationUpdates = true;
// create the POJO to store the last known location
mCurrentGeolocationEntity = new CurrentGeolocationEntity();
buildGoogleApiClient();
createLocationRequest();
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected to GoggleApiClient");
if (mCurrentGeolocationEntity.getmLastLocation() == null) {
mCurrentGeolocationEntity.setmLastLocation(LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient));
}
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
my problem is I don't know where place exactly the function to retrieve data from the server. I'm using Volley library and I have already written the data. What do you suggest?
If you are concerned about the visibility of the fragment due to it not being loaded yet, you can try 2 things. The first is using ViewTreeObserver. You could use ViewTreeObserver to wait for your fragment or view to finish loading then fetch your data. Here is an example using a view:
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// Do your fetch and data insert to view here.
...
}
});
}
The next one you can try is to do your fetching using a runnable. Example:
YourLayout = (RelativeLayout) findViewById(R.id.BoxesLinearLayout);
YourLayout .post(new Runnable() {
#Override
public void run() {
// Do your fetch and data insert to view here.
...
}
});

How do I make a google plus button with a custom layout in android?

I want to create a custom layout for my google plus button, any ideas? I've tried calling the OnClickEvent of the google plus button (that doesn't work) and I've tried changing the background image. Source code:
<com.google.android.gms.plus.PlusOneButton
xmlns:plus="http://schemas.android.com/apk/lib/com.google.android.gms.plus"
android:id="#+id/plus_one_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
plus:size="standard"
plus:annotation="inline"/>
holder.mPlusOneButton = (PlusOneButton) holder.content.findViewById(R.id.plus_one_button);
holder.mPlusOneButton.initialize("http://www.xxx.xx/", 0);
Add a custom button to your layout
Set OnClickListener to your custom button
Use the PlusClient as described here to handle the login procedure
As example I can provide my controller class for handling Google Plus login:
public class GooglePlusLoginController implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {
public static final int REQUEST_CODE_SIGN_IN = 100;
private PlusClient googlePlusClient;
private ConnectionResult connectionResult;
private Activity activity;
public GooglePlusLoginController(Activity activity) {
this.activity = activity;
googlePlusClient = new PlusClient.Builder(activity, this, this)
.setActions("http://schemas.google.com/AddActivity")
.setScopes(Scopes.PLUS_LOGIN) // Space separated list of scopes
.build();
googlePlusClient.connect();
}
// call this method in your click handler
public void login() {
try {
connectionResult.startResolutionForResult(activity, REQUEST_CODE_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
googlePlusClient.connect();
}
}
// call this method in your activity's onActivityResult
public void onActivityResult() {
if(!googlePlusClient.isConnected() && !googlePlusClient.isConnecting()) {
googlePlusClient.connect();
}
}
#Override
public void onConnected(Bundle bundle) {
// connected, you can now get user's data from
// googlePlusClient.getCurrentPerson()
}
#Override
public void onDisconnected() {
}
#Override
public void onConnectionFailed(ConnectionResult result) {
connectionResult = result;
}
private void logout() {
if(googlePlusClient.isConnected()) {
googlePlusClient.clearDefaultAccount();
googlePlusClient.disconnect();
googlePlusClient.connect();
}
}
}

Categories

Resources