Broadcast Reciever in android with Intent.ACTION_BATTERY_CHANGED not working in background - android-broadcast

I am developing an android application in which I have to get the battery charge % through broadcast receiver and display a toast in background when battery is changed.
I have registered receiver and intent filer required to get the value.
It runs fine when app is opened but it does not provide value when app is closed.
Please suggest what should I do in order to run the toast with value in background when app is closed
public class MainActivity extends Activity {
private TextView batteryPercent;
int level;
private void getBatteryPercentage() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int currentLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
level = -1;
if (currentLevel >= 0 && scale > 0) {
level = (currentLevel * 100) / scale;
}
batteryPercent.setText("Battery Level Remaining: " + level + "%");
CountDownTimer cdt = new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
Toast.makeText(getApplicationContext(),"Level "+Integer.toString(level),
Toast.LENGTH_LONG).show();
;
}
}
.start();
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
/* #Override*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
batteryPercent = (TextView) this.findViewById(R.id.batteryLevel);
getBatteryPercentage();
}
Blockquote

You need to have the same Broadcast receiver registered in the Manifest with its own separate class
Like this.
<BroadcastReceiver
android:name = "class name">
<intent-filter>
<action android:name = " your action here"/>
</intent-filter>
</BroadcastReceiver>
In this case your action is android.intent.action.BATTERY_CHANGED so the code would be
<BroadcastReceiver
android:name = "class name">
<intent-filter>
<action android:name = "android.intent.action.BATTERY_CHANGED"/>
</intent-filter>
</BroadcastReceiver>
Hope this helps you

Related

create xamarin process never end

I have a plan and want to periodically check a URL every 5 minutes(NOTIFY CENTER SERVER(Listener)).
My problem: Once the program closes, the process closes
Is it possible that the project will not be shut down if the original program is closed ?
My Code After Changed Worked with : Matcha.BackgroundService
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Matcha.BackgroundService.Droid;
using Matcha.BackgroundService;
using System.Threading.Tasks;
using Android.Util;
using System.Threading;
using AndroidApp = Android.App.Application;
using Android.Content;
using Android.Support.V4.App;
using Android.Graphics;
namespace Solution.Droid
{
[Activity(Label = "Solution", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
private NotificationManager _manager;
private bool _channelInitialized = false;
public const int _pendingIntentId = 0;
public int _channelID = 10001;
private long _mssageID=0;
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
BackgroundAggregator.Init(this);
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
protected override void OnStart()
{
base.OnStart();
//Register Periodic Tasks
var _notifyTASK = new DevinuxTaskPeriodic(10);
_notifyTASK.DoTask += () =>
{
SendNotify("salam", DateTime.Now.ToString());
};
BackgroundAggregatorService.Add(() => _notifyTASK);
BackgroundAggregatorService.StartBackgroundService();
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
public int SendNotify(string title, string message)
{
_mssageID++;
if (!_channelInitialized)
{
CreateNotificationChannel();
}
Intent intent = new Intent(AndroidApp.Context, typeof(MainActivity));
PendingIntent pendingIntent = PendingIntent.GetActivity(AndroidApp.Context, _pendingIntentId, intent, PendingIntentFlags.OneShot);
NotificationCompat.Builder builder = new NotificationCompat.Builder(AndroidApp.Context, _channelID.ToString())
.SetContentIntent(pendingIntent)
.SetContentTitle(title)
.SetContentText(message)
.SetLargeIcon(BitmapFactory.DecodeResource(AndroidApp.Context.Resources, Resource.Drawable.notification_template_icon_bg))
.SetSmallIcon(Resource.Drawable.notification_template_icon_bg)
.SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate);
Notification notification = builder.Build();
_manager.Notify((int)_mssageID, notification);
return (int)_mssageID;
}
void CreateNotificationChannel()
{
_manager = (NotificationManager)AndroidApp.Context.GetSystemService(AndroidApp.NotificationService);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var channelNameJava = new Java.Lang.String("Solution");
var channel = new NotificationChannel(_channelID.ToString(), channelNameJava, NotificationImportance.Default)
{
Description = "My Company Notify Camp."
};
_manager.CreateNotificationChannel(channel);
}
_channelInitialized = true;
}
public class DevinuxTaskPeriodic : IPeriodicTask
{
public bool use { set; get; } = false;
public delegate void DoArgs();
public event DoArgs DoTask;
public DevinuxTaskPeriodic(int seconds)
{
Interval = TimeSpan.FromSeconds(seconds);
}
public TimeSpan Interval { get; set; }
public Task<bool> StartJob()
{
if (!use)
{
Timer tmr = new Timer((o) => {
if (DoTask != null)
{
DoTask();
}
}, null, 0, (int)Interval.TotalSeconds*1000);
}
use = true;
return new Task<bool>(() => true);
}
}
}
}
Yes, it is possible to run processes even when the original program/app is not in the foreground.
You are entering the territory of "backgrounding" which is less simple to do. There isn't an inbuilt/official way of performing backgrounding using Xamarin.Forms, so you will have to either create a dependency service (shown here), or try using Shiny.
If you follow the dependency services route, you just need to follow the official iOS & Android tutorials and implement them in your Native project. Note that if you only need a periodic alarm, Android provides a simpler Alarm/PowerManager that you can use.

Android Service binding with MvvmCross

I am developing xamarin.Android app in MvvmCross. I want to call a service even when the App is backgrounded and a user is logged in. The problem is, I want to call this service within every say 2 hours whether the app is in foreground or background, just the user of the App needs to be logged in.
Intent loggedintent = new Intent(this,typeof(DeviceLoginHelper));
loggedintent.PutExtra("LoggedIn", true);
StartService(loggedintent);
I have written an android service:
[Service]
public class DeviceLoginHelper : IntentService
{
protected override void OnHandleIntent(Intent intent)
{
try
{
if(intent.HasExtra("LoggedIn"))
{
}
}
catch(Exception ex) { }
}
}
But how can I implement a timer? Where do I initialise and handle event to the timer. And when timer is elapsed when should I call ?
public override void OnDestroy()
{
try
{
base.OnDestroy();
}
catch(Exception ex){}
}
and when a user loges out i want to stop this service. Where do I put the call StopService() in MvvmCross
I would not use a Timer. Instead you should configure the AlarmManager.
[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
private static AlarmManager alarmMgr;
private static PendingIntent alarmIntent;
public const int NOTIFICATION_ID = 1;
public const int IDLE_TIME_MS = 30 * 1000; // 30-seconds (update here)
private NotificationManager mNotificationManager;
Notification.Builder builder;
public override void OnReceive(Context context, Intent intent)
{
// Do something when alarm triggers (here I'm building notification)
BuildNotification(context);
// reschedule alarm
ScheduleAlarm(IDLE_TIME_MS);
}
public static Context ApplicationContext { get; set; }
public static void ScheduleAlarm(int milliseconds)
{
if (milliseconds == 0) return;
alarmMgr = (AlarmManager)ApplicationContext.GetSystemService(Context.AlarmService);
var intent = new Intent(ApplicationContext, typeof(AlarmReceiver));
alarmIntent = PendingIntent.GetBroadcast(ApplicationContext, 0, intent, 0);
alarmMgr.Set(AlarmType.ElapsedRealtimeWakeup,
SystemClock.ElapsedRealtime() + milliseconds, alarmIntent);
}
private void BuildNotification(Context context)
{
mNotificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
var contentIntent = PendingIntent.GetActivity(context, 0, new Intent(context, typeof(MainView)), 0);
var message = $"Time is up";
var mBuilder = new Notification.Builder(context)
.SetAutoCancel(true)
.SetPriority(NotificationCompat.PriorityMax)
.SetDefaults(NotificationDefaults.All)
.SetContentTitle("Time is up")
.SetStyle(new Notification.BigTextStyle()
.BigText(message))
.SetContentText(message)
.SetSmallIcon(Resource.Drawable.ic_launcher);
mBuilder.SetContentIntent(contentIntent);
mNotificationManager.Notify(NOTIFICATION_ID, mBuilder.Build());
}
}
In your startup code, simply call:
AlarmReceiver.ApplicationContext = context;
AlarmReceiver.ScheduleAlarm(timeInMs);

SeekBar won't run when media player are playing on xamarin android

The SeekBar widget is an interactive slider that allows the user to select one value from a range of values. As the user moves the slider left or right, the value of the SeekBar will change
public int getProgressPercentage(int currentDuration, int totalDuration)
{
int percentage;
int currentSeconds = (int)(currentDuration / 1000);
int totalSeconds = (int)(totalDuration / 1000);
//calculating percentage
percentage = (((int)currentSeconds) / totalSeconds) * 100;
return percentage;
}
public void UpdatedTimerTask()
{
//Displaying time
//txtCurrentTimer.Text = utils.miliSecondsTotimer (player.CurrentPosition);
//txtTotalTimer.Text = utils.miliSecondsTotimer (player.Duration);
//Updating progress bar(seekbar)
int progress=(int)(utils.getProgressPercentage(player.CurrentPosition,player.Duration));
seekBar.Progress = progress;
}
void SeekBar_ProgressChanged (object sender, SeekBar.ProgressChangedEventArgs e)
{
UpdatedTimerTask ();
}
public void StartMedia(string url_string)
{
player = new MediaPlayer ();
seekBar.Progress = 0;
seekBar.Max = 100;
player.Reset ();
player.SetAudioStreamType (Stream.Music);
player.SetDataSource(url_string);
player.Prepare();
player.Start ();
imgPlayorPause.SetImageResource (Resource.Drawable.ic_pause_black_36dp);
UpdatedTimerTask ();
}
seekBar.SetOnSeekBarChangeListener (this); has some invalid argument.
SeekBar won't run when media player are playing.
You have two options:
SetOnSeekBarChangeListener()
If you want to use SetOnSeekBarChangeListener you have to implement IOnSeekBarChangeListener in the class of this (usually your activity. The disadvantage of this is, that you can only have one event listener.
[Activity]
public class MyActivity : Activity, SeekBar.IOnSeekBarChangeListener
{
protected override void OnCreate(Bundle bundle)
{
// ...
seekbar.SetOnSeekBarChangeListener(this);
}
public void OnProgressChanged(SeekBar seekBar, int progress, bool fromUser)
{
// do some stuff
}
public void OnStartTrackingTouch(SeekBar seekBar)
{
}
public void OnStopTrackingTouch(SeekBar seekBar)
{
}
}
ProgressChanged Event
Xamarin maps Java methods that are called like SetXyzListener to the event called Xyz.
If you want to use ProgressChanged you have to register your handler with seekbar.ProgressChanged += SeekbarOnProgressChanged. The disadvantage of this is, that you have to ensure to remove the handler with seekbar.ProgressChanged -= SeekbarOnProgressChanged when you do not need the event anymore. You should do this in the counterpart of the lifecycle method where you have added the handler. In the following example I used OnResume and OnPause.
[Activity]
public class MyActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// ...
}
protected override void OnResume()
{
base.OnResume();
seekbar.ProgressChanged += SeekbarOnProgressChanged;
}
protected override void OnPause()
{
seekbar.ProgressChanged -= SeekbarOnProgressChanged;
base.OnPause();
}
private void SeekbarOnProgressChanged(object sender, SeekBar.ProgressChangedEventArgs progressChangedEventArgs)
{
// do some stuff
}
}

How to get Android Application to push notifications after ui thread is closed

How to get push notification working after manually closing UI on Android?
Hi, I need some help, Couldn't find any solutions by searching.
Application basically is like any other messaging applications, ex. Whatsapp.
I have MessageService running as own process, even UI closed, it stays alive.
This is how my application basically works:
MainActivity start service
MessageService send broadCast to
messageReceiver gets broadCast and run messageLoader
MessagesLoader extends AsyncTask gets changes from database
MessagesLoader push notification.
Every these parts working correctly when UI running
When I close UI, messageService restarts again, but no push notifications after UI closed.
Any help to get this work would be appreciated.
Thanks
Here is some code snippet to understand how my thing works..
MainActivity.java
...........................
#Override
protected void onResume() {
super.onResume();
serviceIntent = new Intent(getApplicationContext(), MessageService.class);
startService(serviceIntent);
registerReceiver(messageReceiver, new IntentFilter(MessageService.MESSAGES_BROADCAST_ACTION));
}
...........................
MessageService.java
public class MessageService extends Service {
Updater updater;
BroadcastReceiver messageBroadcaster;
Intent intent;
Context context;
static final public String MESSAGES_BROADCAST_ACTION = "com.<Your Package>";
public MessageService() {
}
#Override
public IBinder onBind(Intent intent) {
this.intent = intent;
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
this.updater = new Updater();
this.context = getApplicationContext();
this.intent = new Intent(this, NotificationActivity.class);
Toast.makeText(this, "Message Service Created", Toast.LENGTH_LONG).show();
}
#Override
public synchronized int onStartCommand(Intent intent, int flags, int startId) {
if (!updater.isRunning()) {
updater.start();
updater.isRunning = true;
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public synchronized void onDestroy() {
super.onDestroy();
if (updater.isRunning) {
updater.interrupt();
updater.isRunning = false;
updater = null;
}
Toast.makeText(this, "Message Service Destroyed", Toast.LENGTH_LONG).show();
}
class Updater extends Thread {
public boolean isRunning = false;
public long DELAY = 2500;
#Override
public void run() {
super.run();
isRunning = true;
while (isRunning) {
sendResult();
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
isRunning = false;
}
}
}
public boolean isRunning() {
return this.isRunning;
}
}
public void sendResult() {
sendBroadcast(intent);
}
}
MessageReceiver.java
public class MessageReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, MessageService.class);
context.startService(serviceIntent);
new MessagesLoader(context).execute();
}
}
MessageLoader.java
public class MessagesLoader extends AsyncTask<String,Void,String> {
public MessagesLoader(Context context) {
this.context = context;
this.intent = new Intent(this.context, ChatsActivity.class);
this.prev_count = prev_count;
Intent intent = new Intent(context, ChatsActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
this.mBuilder = new android.support.v4.app.NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("YOUR APP");
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
StringBuffer result = new StringBuffer("");
try {
URL url = new URL("http://yourURL.com/get_data.php");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoOutput(true);
String urlParameters = "<OWN PARAMETERS>";
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
con.connect();
InputStream inputStream = con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
return new String(result);
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
initData(result);
}
public void initData(String result) {
// Actually Store Data to sharedPreferences
String error = "";
JSONObject obj = new JSONObject();
// ...ETC
int count = 5;
showNotification(5);
}
public void showNotification(int count) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(this.context, ChatsActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this.context, 0, mIntent, 0);
Intent cIntent = new Intent(this.context, NotificationActionService.class);
PendingIntent cPIntent = PendingIntent.getService(this.context, 0, cIntent, 0);
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.bigText("YOUR BIG TEXT");
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder
.setContentIntent(pIntent)
.setContentText("YOUR CONTENT TEXT")
.setAutoCancel(true)
.setLights(R.color.white, 1000, 500)
.setSound(soundUri)
.setGroup("YOUR GROUP")
.setTicker("YOUR TICKER TEXT")
.setWhen(System.currentTimeMillis())
.setCategory("YOUR CATEGORY")
.setStyle(bigTextStyle)
.addAction(0, "Show Messages", pIntent);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(mIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yourpackage" >
android:versionCode="1"
android:versionName="1.0"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:configChanges="orientation"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.yourpackage.MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
<service android:name="com.yourpackage.MessageService"
android:process=":messageService"
android:enabled="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/messageService">
<intent-filter>
<action android:name="com.yourpackage.MessageService" />
</intent-filter>
</service>
<receiver android:name="com.yourpackage.MessageReceiver">
<intent-filter>
<action android:name="com.yourpackage.MessageReceiver" />
</intent-filter>
</receiver>
</application>
</manifest>
I've found the solution. Now my application is always showing me new messages info even without UI running.
Here is solution to fix this problem.
MainActivity.java
#Override
protected void onResume() {
super.onresume();
serviceIntent = new Intent(getApplicationContext(), MessageService.class);
startService(serviceIntent);
/* COMMENTED OUT LINE BELOW */
//registerReceiver(messageReceiver, new IntentFilter(MessageService.MESSAGES_BROADCAST_ACTION));
}
MessageService.java
#Override
public void onCreate() {
super.onCreate();
updater = new Updater();
context = getApplicationContext();
/* AND ADDED THAT LINE HERE AND */
registerReceiver(messageReceiver, new IntentFilter(MESSAGES_BROADCAST_ACTION));
intent = new Intent(MESSAGES_BROADCAST_ACTION);
Toast.makeText(this, "Message Service Created", Toast.LENGTH_LONG).show();
}

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