Google Maps activity. Why my code don't give me the location of the phone? - location

I'm trying to make an app that take locations of devices and put into a google maps activity with firebase and realtime DB. I have this code and i don't know why don't give me the location of the dispositive. Location is null into the onSuccess method.
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient fusedLocationProviderClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
Toast.makeText(MainActivity.this, "No veas tu que bien",Toast.LENGTH_SHORT).show();
Log.e("Latitud: ", +location.getLatitude() + "Longitud: " + location.getLongitude());
}
}
});
}

Related

How About onActivityResult when I want to read multiple file from storage

How About onActivityResult when I want to read multiple file form storage
In this xml form I have to take multiple image file by clicking different different button from the app external storage but their is a difficulties on ActivityResult override method calling , because it call automatically and can't be call multiple time for for different different button
It's working fine for single file picking and get image URI.
So how can I fix the ActivityResult override method for different different button in a single activity
public class Application_Form extends AppCompatActivity {
ActivityApplicationBinding binding;
boolean isOnlyImageAllowed = true;
private static final int PICK_PHOTO = 1958;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityApplicationBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
//check user storage permission
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
binding.form4.choosePropertyFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, PICK_PHOTO);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO) {
Uri imageUri = data.getData();
binding.form4.selectedPropertyFile.setText("" + imageUri.getLastPathSegment());
}
}
}
Taking a array to pick photo then check with if else statement by array index
public class Application_Form extends AppCompatActivity {
ActivityApplicationBinding binding;
boolean isOnlyImageAllowed = true;
private static int[] PICK_PHOTO={0,1,2,3,4,5} ;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityApplicationBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
binding.appBar.title.setText("লাইসেন্সের জন্য আবেদন করুন");
binding.appBar.back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
//check user storage permission
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
binding.form4.choosePropertyFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, 0);
}
});
binding.form4.chooseBankCertificate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO[0]) {
Uri imageUri = data.getData();
binding.form4.selectedPropertyFile.setText("" + imageUri.getLastPathSegment());
}
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO[1]) {
Uri imageUri = data.getData();
binding.form4.selectedBankCertificate.setText("" + imageUri.getLastPathSegment());
}
}
}

How to implement Local Push notification in Xamarin Android

I am having the Xamarin.Forms application. I want to implement the local push notification for Android platform, through which an application can receive the notification whenever the app is minimized or phone is locked. I also want to wake-up the phone and display the notification on the lock screen whenever the phone is locked.
As I am new in this kindly help me.
Thanks in advance.
Vivek
I think you should consider two things.
1.Listen for the screen lock:
create a ScreenListener.cs :
public class ScreenListener
{
private Context mContext;
private ScreenBroadcastReceiver mScreenReceiver;
private static ScreenStateListener mScreenStateListener;
public ScreenListener(Context context)
{
mContext = context;
mScreenReceiver = new ScreenBroadcastReceiver();
}
/**
* screen BroadcastReceiver
*/
private class ScreenBroadcastReceiver : BroadcastReceiver
{
private String action = null;
public override void OnReceive(Context context, Intent intent)
{
action = intent.Action;
if (Intent.ActionScreenOn == action)
{ // screen on
mScreenStateListener.onScreenOn();
}
else if (Intent.ActionScreenOff == action)
{ // screen off
mScreenStateListener.onScreenOff();
}
else if (Intent.ActionUserPresent == action)
{ // unlock
mScreenStateListener.onUserPresent();
}
}
}
/**
* begin to listen screen state
*
* #param listener
*/
public void begin(ScreenStateListener listener)
{
mScreenStateListener = listener;
registerListener();
getScreenState();
}
/**
* get screen state
*/
private void getScreenState()
{
PowerManager manager = (PowerManager)mContext
.GetSystemService(Context.PowerService);
if (manager.IsScreenOn)
{
if (mScreenStateListener != null)
{
mScreenStateListener.onScreenOn();
}
}
else
{
if (mScreenStateListener != null)
{
mScreenStateListener.onScreenOff();
}
}
}
/**
* stop listen screen state
*/
public void unregisterListener()
{
mContext.UnregisterReceiver(mScreenReceiver);
}
/**
* regist screen state broadcast
*/
private void registerListener()
{
IntentFilter filter = new IntentFilter();
filter.AddAction(Intent.ActionScreenOn);
filter.AddAction(Intent.ActionScreenOff);
filter.AddAction(Intent.ActionUserPresent);
mContext.RegisterReceiver(mScreenReceiver, filter);
}
public interface ScreenStateListener
{// Returns screen status information to the caller
void onScreenOn();
void onScreenOff();
void onUserPresent();
}
}
then in the MainActivity.cs:
public class MainActivity : AppCompatActivity,ScreenStateListener
{
ScreenListener mScreenListener;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
mScreenListener = new ScreenListener(this);
}
protected override void OnDestroy()
{
base.OnDestroy();
mScreenListener.unregisterListener();
}
protected override void OnResume()
{
base.OnResume();
mScreenListener.begin(this);
}
public void onScreenOn()
{
Console.WriteLine("onScreenOn");
}
public void onScreenOff()
{
Console.WriteLine("onScreenOff");
}
public void onUserPresent()
{
Console.WriteLine("onUserPresent");
}
}
2.creat loacal Notification:
finally you just push the notification in the onScreenOff() method.
What you need is push notifications not local notifications. Local notifications only work if your app is running. Push notifications are handled by OS (Android in this case). Xamarin is recommending using Firebase service to handle it. Procedure is pretty straight forward all what you have to do is follow Tutorial from official Xamarin site.
Remote Notifications with Firebase Cloud Messaging

Background Service Location Changed Not Fired Xamarin Android

I need to retrieve the real-time location of the device, I had implement ILocationListener in my Service Class as I want this to run even after the app is in the background or closed I have referred - this
and it seems not working for me even if I change my device location the location change event is not fired
My Service Class with Implemented ILocationListener
[Service]
public class LocationService : Service, ILocationListener
{
public event EventHandler<LocationChangedEventArgs> LocationChanged = delegate { };
public event EventHandler<ProviderDisabledEventArgs> ProviderDisabled = delegate { };
public event EventHandler<ProviderEnabledEventArgs> ProviderEnabled = delegate { };
public event EventHandler<StatusChangedEventArgs> StatusChanged = delegate { };
public LocationService()
{
}
// Set our location manager as the system location service
protected LocationManager LocMgr = Android.App.Application.Context.GetSystemService ("location") as LocationManager;
readonly string logTag = "LocationService";
IBinder binder;
public override void OnCreate ()
{
base.OnCreate ();
Log.Debug (logTag, "OnCreate called in the Location Service");
}
// This gets called when StartService is called in our App class
[Obsolete("deprecated in base class")]
public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug (logTag, "LocationService started");
return StartCommandResult.Sticky;
}
// This gets called once, the first time any client bind to the Service
// and returns an instance of the LocationServiceBinder. All future clients will
// reuse the same instance of the binder
public override IBinder OnBind (Intent intent)
{
Log.Debug (logTag, "Client now bound to service");
binder = new LocationServiceBinder (this);
return binder;
}
// Handle location updates from the location manager
public void StartLocationUpdates ()
{
//we can set different location criteria based on requirements for our app -
//for example, we might want to preserve power, or get extreme accuracy
var locationCriteria = new Criteria();
locationCriteria.Accuracy = Accuracy.NoRequirement;
locationCriteria.PowerRequirement = Power.NoRequirement;
// get provider: GPS, Network, etc.
var locationProvider = LocMgr.GetBestProvider(locationCriteria, true);
Log.Debug (logTag, string.Format ("You are about to get location updates via {0}", locationProvider));
// Get an initial fix on location
LocMgr.RequestLocationUpdates(locationProvider, 2000, 0, this);
Log.Debug (logTag, "Now sending location updates");
}
public override void OnDestroy ()
{
base.OnDestroy ();
Log.Debug (logTag, "Service has been terminated");
// Stop getting updates from the location manager:
LocMgr.RemoveUpdates(this);
}
My Binder Class
public class LocationServiceBinder : Binder
{
public LocationService Service
{
get { return this.service; }
} protected LocationService service;
public bool IsBound { get; set; }
// constructor
public LocationServiceBinder (LocationService service)
{
this.service = service;
}
}
public class LocationServiceConnection : Java.Lang.Object, IServiceConnection
{
public event EventHandler<ServiceConnectedEventArgs> ServiceConnected = delegate {};
public LocationServiceBinder Binder
{
get { return this.binder; }
set { this.binder = value; }
}
protected LocationServiceBinder binder;
public LocationServiceConnection (LocationServiceBinder binder)
{
if (binder != null) {
this.binder = binder;
}
}
// This gets called when a client tries to bind to the Service with an Intent and an
// instance of the ServiceConnection. The system will locate a binder associated with the
// running Service
public void OnServiceConnected (ComponentName name, IBinder service)
{
// cast the binder located by the OS as our local binder subclass
LocationServiceBinder serviceBinder = service as LocationServiceBinder;
if (serviceBinder != null) {
this.binder = serviceBinder;
this.binder.IsBound = true;
Log.Debug ( "ServiceConnection", "OnServiceConnected Called" );
// raise the service connected event
this.ServiceConnected(this, new ServiceConnectedEventArgs () { Binder = service } );
// now that the Service is bound, we can start gathering some location data
serviceBinder.Service.StartLocationUpdates();
}
}
// This will be called when the Service unbinds, or when the app crashes
public void OnServiceDisconnected (ComponentName name)
{
this.binder.IsBound = false;
Log.Debug ( "ServiceConnection", "Service unbound" );
}
}
public class ServiceConnectedEventArgs : EventArgs
{
public IBinder Binder { get; set; }
}
My MainActivity
public class MainActivity : Activity
{
readonly string logTag = "MainActivity";
// make our labels
TextView latText;
TextView longText;
TextView altText;
TextView speedText;
TextView bearText;
TextView accText;
#region Lifecycle
//Lifecycle stages
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
Log.Debug (logTag, "OnCreate: Location app is becoming active");
SetContentView (Resource.Layout.Main);
// This event fires when the ServiceConnection lets the client (our App class) know that
// the Service is connected. We use this event to start updating the UI with location
// updates from the Service
App.Current.LocationServiceConnected += (object sender, ServiceConnectedEventArgs e) => {
Log.Debug (logTag, "ServiceConnected Event Raised");
// notifies us of location changes from the system
App.Current.LocationService.LocationChanged += HandleLocationChanged;
//notifies us of user changes to the location provider (ie the user disables or enables GPS)
App.Current.LocationService.ProviderDisabled += HandleProviderDisabled;
App.Current.LocationService.ProviderEnabled += HandleProviderEnabled;
// notifies us of the changing status of a provider (ie GPS no longer available)
App.Current.LocationService.StatusChanged += HandleStatusChanged;
};
latText = FindViewById<TextView> (Resource.Id.lat);
longText = FindViewById<TextView> (Resource.Id.longx);
altText = FindViewById<TextView> (Resource.Id.alt);
speedText = FindViewById<TextView> (Resource.Id.speed);
bearText = FindViewById<TextView> (Resource.Id.bear);
accText = FindViewById<TextView> (Resource.Id.acc);
altText.Text = "altitude";
speedText.Text = "speed";
bearText.Text = "bearing";
accText.Text = "accuracy";
// Start the location service:
App.StartLocationService();
}
protected override void OnPause()
{
Log.Debug (logTag, "OnPause: Location app is moving to background");
base.OnPause();
}
protected override void OnResume()
{
Log.Debug (logTag, "OnResume: Location app is moving into foreground");
base.OnResume();
}
protected override void OnDestroy ()
{
Log.Debug (logTag, "OnDestroy: Location app is becoming inactive");
base.OnDestroy ();
// Stop the location service:
App.StopLocationService();
}
#endregion
#region Android Location Service methods
///<summary>
/// Updates UI with location data
/// </summary>
public void HandleLocationChanged(object sender, LocationChangedEventArgs e)
{
Android.Locations.Location location = e.Location;
Log.Debug (logTag, "Foreground updating");
// these events are on a background thread, need to update on the UI thread
RunOnUiThread (() => {
latText.Text = String.Format ("Latitude: {0}", location.Latitude);
longText.Text = String.Format ("Longitude: {0}", location.Longitude);
altText.Text = String.Format ("Altitude: {0}", location.Altitude);
speedText.Text = String.Format ("Speed: {0}", location.Speed);
accText.Text = String.Format ("Accuracy: {0}", location.Accuracy);
bearText.Text = String.Format ("Bearing: {0}", location.Bearing);
});
}
public void HandleProviderDisabled(object sender, ProviderDisabledEventArgs e)
{
Log.Debug (logTag, "Location provider disabled event raised");
}
public void HandleProviderEnabled(object sender, ProviderEnabledEventArgs e)
{
Log.Debug (logTag, "Location provider enabled event raised");
}
public void HandleStatusChanged(object sender, StatusChangedEventArgs e)
{
Log.Debug (logTag, "Location status changed, event raised");
}
#endregion
}
the above public void HandleLocationChanged(object sender, LocationChangedEventArgs e) {}
never get fired on my device location change

Intent function while running application get crashed

When clicked on this textview the app get crashed and didn't change the activity it is suppose to switch from main activity to another how to resolve it?
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etEmail;
private EditText etPassword;
private TextView tvLogin;
private TextView tvSignup;
private Button btnSignin, btMr;
private FirebaseAuth firebaseAuth;
AwesomeValidation awesomeValidation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);
updateUI();
firebaseAuth = FirebaseAuth.getInstance();
}
private void updateUI() {
etEmail = (EditText) findViewById(R.id.etEmail);
tvSignup = (TextView) findViewById(R.id.tvSignup);
etPassword = (EditText) findViewById(R.id.etPassword);
tvLogin = (TextView) findViewById(R.id.tvLogin);
btnSignin = (Button) findViewById(R.id.btnLogin);
tvSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signup();
}
public void signup() {
Intent i = new Intent(MainActivity.this, Registration.class);
startActivity(i);
}
});
Here I used awesome validation for validating my form but while running the app shows the toast message, but do not register the user to fire base it validate my form but do not register
String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d])(?=.*[~`!##\\$%\\^&\\*\\(\\)\\-_\\+=\\{\\}\\[\\]\\|\\;:\"<>,./\\?]).{8,}";
awesomeValidation.addValidation(MainActivity.this, R.id.etEmail, android.util.Patterns.EMAIL_ADDRESS, R.string.etEmailerr);
awesomeValidation.addValidation(MainActivity.this, R.id.etPassword, regexPassword, R.string.etPasserr);
btnSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (awesomeValidation.validate()) {
Toast.makeText(MainActivity.this, "Data Recieved Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();
}
}
});
}
This part register the user to firebase, but after adding this awesome validation this do not work app shows a toast message from validation and do not register or change activity how can i merge both so that my form get validate and also get register to my firebase auth
public void btnLogin_Click(View v) {
final ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "Please Wait....", "Processing...", true);
(firebaseAuth.signInWithEmailAndPassword(etEmail.getText().toString(), etPassword.getText().toString()))
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "LOGIN SUCCESSFULL", Toast.LENGTH_LONG).show();
Intent signin = new Intent(MainActivity.this, Dashboard.class);
startActivity(signin);
} else {
Log.e("ERROR", task.getException().toString());
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onClick(View view) {
}
}
this is due to the regex function.
the values used in activity1 regex get differ in another activity2 due to which the intent can't switch from one activity to another.
values passed the the regex should be same in all the activity linked.

WearableListenerService doesn't receive data

I'm trying to send sensor data from my wear device to the handheld. The problem is that the onMessageReceived function of my WearableListenerService is never called, even though it gets created.
The package names of the wear and mobile apps are the same, also here's the entry for the service in the manifest file:
<service
android:name=".WatchDataReceiver"
android:enabled="true"
android:exported="true" >
</service>
On my handheld in the MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, WatchDataReceiver.class));
setContentView(R.layout.activity_fullscreen);
...
}
On my handheld, the service:
public class WatchDataReceiver extends WearableListenerService {
#Override
public void onCreate() {
super.onCreate();
Log.i(WatchDataReceiver.class.getSimpleName(), "WEAR create");
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.i(WatchDataReceiver.class.getSimpleName(), "WEAR Data changed " );
}
#Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.i(WatchDataReceiver.class.getSimpleName(), "WEAR Message " + messageEvent.getPath());
}
}
On the watch/wear:
public class MainActivity extends Activity implements SensorEventListener {
private static final String LOG_TAG = "Watch: ";
private SensorManager sensorManager;
private Sensor accelerometer;
private GoogleApiClient mGoogleApiClient;
private String msg = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
if (accelerometer != null) {
Log.v(LOG_TAG, "Accelerometer registered!");
}
else {
Log.v(LOG_TAG, "Accelerometer _not_ registered!");
}
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
mGoogleApiClient.connect();
}
#Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER && event.values.length > 0) {
double value_x = event.values[0];
double value_y = event.values[1];
double value_z = event.values[2];
msg = Double.toString(value_x) + ";" + Double.toString(value_y) + ";" + Double.toString(value_z);
sendMessageToHandheld(msg);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//TODO
}
private void sendMessageToHandheld(String msg) {
if (mGoogleApiClient == null)
return;
final String message = msg;
Log.d(LOG_TAG,"sending a message to handheld: "+message);
// use the api client to send the heartbeat value to our handheld
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);
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), message, null);
}
}
}
});
}
}
According to LogCat the correct handheld is found because in sendMessageToHandheld right after the actual sendMessage it do a Log.d with the name of the node.
What am I missing?
You have to add this IntentFilter to your service:
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
It tells the system to take care of the Service lifecycle (ie starting it if needed).

Resources