Android Wear sends message to android mobile - android

I'm new in Android Wear development. I'm trying to make the smartwatch send a string to a mobile app but I don't know how make it work. I've tried to do that following some tutorials, but still nothing works.
Android mobile manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="manuela.com.messagewearableandroid">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".ListenerService"
android:enabled="true">
<intent-filter>
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:scheme="wear" android:host="*" />
</intent-filter>
</service>
</application>
</manifest>
Android Wear manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="manuela.com.messagewearableandroid">
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#android:style/Theme.DeviceDefault">
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ListenerService for mobile:
public class ListenerService extends WearableListenerService {
#Override
public void onMessageReceived(MessageEvent messageEvent) {
super.onMessageReceived(messageEvent);
showToast(messageEvent.getPath());
System.out.println("Arrivato");
}
private void showToast(String message) {
System.out.println("Arrivato");
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
MainActivity for Wear:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initApi();
Button button = (Button) findViewById(R.id.btn_toast);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
/**
* Sets up the button for handling click events.
*/
sendToast();
}
});
}
/**
* Initializes the GoogleApiClient and gets the Node ID of the connected device.
*/
private void initApi() {
client = getGoogleApiClient(this);
retrieveDeviceNode();
}
/**
* Returns a GoogleApiClient that can access the Wear API.
* #param context
* #return A GoogleApiClient that can make calls to the Wear API
*/
private GoogleApiClient getGoogleApiClient(Context context) {
return new GoogleApiClient.Builder(context)
.addApi(Wearable.API)
.build();
}
/**
* Connects to the GoogleApiClient and retrieves the connected device's Node ID. If there are
* multiple connected devices, the first Node ID is returned.
*/
private void retrieveDeviceNode() {
new Thread(new Runnable() {
#Override
public void run() {
client.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
NodeApi.GetConnectedNodesResult result =
Wearable.NodeApi.getConnectedNodes(client).await();
List<Node> nodes = result.getNodes();
if (nodes.size() > 0) {
nodeId = nodes.get(0).getId();
}
client.disconnect();
}
}).start();
}
/**
* Sends a message to the connected mobile device, telling it to show a Toast.
*/
private void sendToast() {
if (nodeId != null) {
new Thread(new Runnable() {
#Override
public void run() {
client.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
Wearable.MessageApi.sendMessage(client, nodeId, MESSAGE, null);
System.out.println("Mandato");
client.disconnect();
}
}).start();
}
}

You may follow this documentation for Sending and Receiving Messages. You send messages using the MessageApi and attach the following items to the message:
An arbitrary payload (optional)
A path that uniquely identifies the message's action
Here's another reference for Sending String from watch to phone.

Related

Having a Service Toast receive SMS messages

Does not display toast message,
I want to show me a toast message when I receive sms but it doesn't work
my Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.video60">
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission-sdk-23 android:name="android.permission.READ_PHONE_STATE"/>
<application
android:name=".G"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".smsReciver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
</application>
</manifest>
my code
public class smsReciver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(G.context,"sms recived in reza",Toast.LENGTH_LONG).show();
}
}
class G
public class G extends Application {
public static Context context;
#Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
}
}
put this on your onReceive function
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"sms recived in reza",Toast.LENGTH_SHORT).show();
}
});

FCM not receiving notification messages

I have my manifest in check, my services in check, my dependencies in check, class variables in check and still no notifications on my device. I'm using my computer to send firebase cloud messages and I should be receiving them on my android phone. However,my android phone is not picking up the notifications. And yes, my android device is in the background as I send the message. Anyone know what my problem is?
Here's the source code:
My Service
public class FirebaseIDMessage extends FirebaseMessagingService {
private static final String TAG = "FirebaseIDMessage";
#Override
public void onNewToken(String s) {
super.onNewToken(s);
String token = s;
Log.d(TAG, "Registered token: = " + token);
sendRegistrationToServer(token);
}
private void sendRegistrationToServer(String token){
}
}
My Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.messaging">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!-- Services -->
<service android:name=".FirebaseIDMessage"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<activity android:name=".MessagingActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
My Activity
public class MessagingActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messaging);
}
}
In your manifest file, you are missing INSTANCE_ID_EVENT
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
This is the intent-filter for the Class extended with FirebaseInstanceIdService
public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService
{
public static final String REGISTRATION_TOKEN = "REG_TOKEN";
#Override
public void onTokenRefresh()
{
String token = FirebaseInstanceId.getInstance().getToken();
Log.e(REGISTRATION_TOKEN,token);
}
}
So, finally the manifest service will be like
<service android:name=".Utils.PushNotification.MyFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
On the log you would have got registered Token. Your all set only if you receive that token.
Goto Firebase console : https://console.firebase.google.com
Choose your project -> From the left side menu -> Choose Cloud Messaging -> New Message
Type your message and then in the TARGET choose Single Device and then copy paste your received token and check on your device for this notification by this way we can confirm you have set all notification related code correctly. If you still face any problem please let know so that I can share some samples.

RegistrationIntentService doesn' t get called

I' m trying to implement push notification in my applicatio but the RegistrationIntentService.class does not get called when i use the method startService.
home activity:
public class HomeActivity extends AriesMobileActivity {
private LinearLayout itemReports;
private LinearLayout itemTickets;
private LinearLayout itemSystems;
private LinearLayout itemManuals;
private LinearLayout itemNotes;
private LinearLayout itemChecklist;
private LinearLayout itemCalendar;
private LinearLayout itemSettings;
private BroadcastReceiver mRegistrationBroadcastReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences
.getBoolean(Preferences.SENT_TOKEN_TO_SERVER, false);
if (sentToken) {
} else {
}
}
};
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, 9000)
.show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
}
Intent intent = new Intent(this,RegistrationIntentService.class);
startService(intent);
if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
this.setContentView(R.layout.layout_home_landscape);
else this.setContentView(R.layout.layout_home_portrait);
itemReports = (LinearLayout) this.findViewById(R.id.item_menu_reports);
itemTickets = (LinearLayout) this.findViewById(R.id.item_menu_tickets);
itemSystems = (LinearLayout) this.findViewById(R.id.item_menu_systems);
itemManuals = (LinearLayout) this.findViewById(R.id.item_menu_manuals);
itemNotes = (LinearLayout) this.findViewById(R.id.item_menu_notes);
itemChecklist = (LinearLayout) this.findViewById(R.id.item_menu_checklist);
itemCalendar = (LinearLayout) this.findViewById(R.id.item_menu_calendar);
itemSettings = (LinearLayout) this.findViewById(R.id.item_menu_settings);
itemReports.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ReportListActivity.class);
startActivity(intent);
}
});
itemTickets.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, TicketListActivity.class);
startActivity(intent);
}
});
itemSystems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, SystemListActivity.class);
startActivity(intent);
}
});
itemSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.startActivity(new Intent(context, SettingsActivity.class));
}
});
itemManuals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ManualsListActivity.class);
startActivity(intent);
}
});
itemCalendar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CalendarActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Preferences.REGISTRATION_COMPLETE));
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
}
RegistrationIntentService:
public class RegistrationIntentService extends IntentService {
private static final String[] TOPICS = {"global"};
public RegistrationIntentService() {
super("RegistrationIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
// [START register_for_gcm]
// Initially this call goes out to the network to retrieve the token, subsequent calls
// are local.
// R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
// See https://developers.google.com/cloud-messaging/android/start for details on this file.
// [START get_token]
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken("312109676786",
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
// [END get_token]
Log.i("RegistrationIntentService", "GCM Registration Token: " + token);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(token);
// Subscribe to topic channels
subscribeTopics(token);
// You should store a boolean that indicates whether the generated token has been
// sent to your server. If the boolean is false, send the token to your server,
// otherwise your server should have already received the token.
sharedPreferences.edit().putBoolean(Preferences.SENT_TOKEN_TO_SERVER, true).apply();
// [END register_for_gcm]
} catch (Exception e) {
Log.d("RegistrationIntentService", "Failed to complete token refresh", e);
// If an exception happens while fetching the new token or updating our registration data
// on a third-party server, this ensures that we'll attempt the update at a later time.
sharedPreferences.edit().putBoolean(Preferences.SENT_TOKEN_TO_SERVER, false).apply();
}
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(Preferences.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
/**
* Persist registration to third-party servers.
*
* Modify this method to associate the user's GCM registration token with any server-side account
* maintained by your application.
*
* #param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
/**
* Subscribe to any GCM topics of interest, as defined by the TOPICS constant.
*
* #param token GCM token
* #throws IOException if unable to reach the GCM PubSub service
*/
// [START subscribe_topics]
private void subscribeTopics(String token) throws IOException {
GcmPubSub pubSub = GcmPubSub.getInstance(this);
for (String topic : TOPICS) {
pubSub.subscribe(token, "/topics/" + topic, null);
}
}
// [END subscribe_topics]
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ngs.ariesmobile"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.verivo.examples.pushandalerttests.permission.C2D_MESSAGE" />
<permission android:name="com.example.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
<application
android:name=".AriesMobileApplication"
android:allowBackup="true"
android:icon="#drawable/app_logo"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo.Light.NoActionBar" >
<service
android:name=".AriesMobileGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name=".AriesMobileInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<service android:name=".RegistrationIntentService" android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.gcm" />
</intent-filter>
</receiver>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<receiver
android:name="com.verivo.examples.pushandalerttests.MyBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.verivo.examples.pushandalerttests" />
</intent-filter>
</receiver>
<receiver android:name=".receivers.PhoneCallReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<activity
android:name=".view.LoginActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".view.HomeActivity"
android:label="#string/app_name" />
<activity
android:name=".view.SignatureCaptureActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name"
android:screenOrientation="sensorLandscape" />
<activity
android:name=".view.SetupHomeActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SetupApiActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SetupLoginActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SetupTechnicianActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SettingsActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SettingsPasswordActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SettingsApiActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SynchronizationActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.ReportCustomerActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name"
android:screenOrientation="sensorLandscape" />
<activity
android:name=".view.ReportInternalActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name"
android:screenOrientation="sensorLandscape" />
<activity
android:name=".view.ReportListActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.TicketListActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.PhoneCallActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent" />
<activity
android:name=".view.SystemActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name"
android:screenOrientation="landscape" />
<activity
android:name=".view.SystemListActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.ReportSummaryActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name"
android:screenOrientation="portrait" />
<activity
android:name=".view.ManualsListActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/title_activity_manuals_list" >
</activity>
<activity
android:name=".view.SystemStoricalActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/title_activity_system_storical" >
</activity>
<activity
android:name=".view.SystemTechnicalPartActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/title_activity_system_technical_part" >
</activity>
<activity
android:name=".view.SystemConsActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/title_activity_system_cons" >
</activity>
<activity
android:name=".view.SystemNoteActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/title_activity_system_note" >
</activity>
<activity
android:name=".view.SystemSupervisionActivity"
android:configChanges="orientation|screenSize"
android:label="#string/title_activity_system_supervision" >
</activity>
<activity
android:name=".view.CalendarActivity"
android:configChanges="orientation|screenSize"
android:label="#string/title_activity_calendar"
android:screenOrientation="landscape" >
</activity>
<activity
android:name=".view.ReportHoursActivity"
android:label="#string/title_activity_report_hours" >
</activity>
<activity
android:name="ngs.ariesmobile.pushnotification.RegisterActivity"
android:label="#string/title_activity_register" >
</activity>
</application>
</manifest>
Thanks in advance

Sync data with android wear

Mobile - Activity
public class TestActivity extends Activity implements DataApi.DataListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private GoogleApiClient mGoogleApiClient;
Button syncBtn;
static int click = 0;
#Override
protected void onStart()
{
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onPause()
{
super.onPause();
mGoogleApiClient.disconnect();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
//mGoogleApiClient.connect();
syncBtn = (Button) findViewById(R.id.syncBtn);
syncBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if(mGoogleApiClient.isConnected())
{
PutDataMapRequest mapRequest = PutDataMapRequest.create(Constants.RUN_UPDATE_NOTIFICATION);
mapRequest.getDataMap().putDouble(Constants.NOTIFICATION_TIMESTAMP, System.currentTimeMillis());
mapRequest.getDataMap().putString(Constants.NOTIFICATION_TITLE, "This is a Title");
mapRequest.getDataMap().putString(Constants.NOTIFICATION_CONTENT, "This is a text with some, notification, see click: "+click++);
PutDataRequest request = mapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(mGoogleApiClient, request).setResultCallback(new ResultCallback<DataApi.DataItemResult>()
{
#Override
public void onResult(DataApi.DataItemResult dataItemResult)
{
if (dataItemResult.getStatus().isSuccess())
{
System.out.println(" syncing successful...."+dataItemResult.getStatus());
}
else
{
System.out.println(" syncing failed.."+dataItemResult.getStatus());
}
}
});
}
else
{
System.out.println("not connected....");
}
}
});
}
#Override
public void onConnected(Bundle bundle)
{
}
#Override
public void onConnectionSuspended(int i)
{
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer)
{
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult)
{
}
}
Getting output from Mobile - activity -
System.out﹕ syncing successful....Status{statusCode=SUCCESS, resolution=null}
But it show no response on Wear - activity(Want to show something on android wear that device has synced).
Below is the code for Wear - activity
public class NotificationUpdateService extends WearableListenerService{
private int notificationId = 001;
#Override
public void onDataChanged(DataEventBuffer dataEvents)
{
super.onDataChanged(dataEvents);
System.out.println("****** ");
for(DataEvent dataEvent: dataEvents)
{
if(dataEvent.getType() == DataEvent.TYPE_CHANGED)
{
DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap();
String title = dataMap.getString("title");
String content = dataMap.getString("content");
System.out.println("title: "+title+" content: "+content);
sendNotification(title, content);
}
}
}
private void sendNotification(String title, String content)
{
Intent viewIntent = new Intent(this, MainActivity.class);
PendingIntent pendingViewIntent = PendingIntent.getActivity(this, 0, viewIntent, 0);
// this intent will be sent when the user swipes the notification to dismiss it
/* Intent dismissIntent = new Intent(Constants.ACTION_DISMISS);
PendingIntent pendingDeleteIntent = PendingIntent.getService(this, 0, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);*/
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(content)
.setContentIntent(pendingViewIntent);
//.setDeleteIntent(pendingDeleteIntent)
Notification notification = builder.build();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(notificationId++, notification);
}}
Android manifest.xml - Wear
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.speedometer" >
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".NotificationUpdateService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
</application></manifest>
Below is the Android manifest for Mobile
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.speedometer" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".LocationActivity"
android:label="#string/title_activity_location" >
</activity>
<activity
android:name=".TestActivity"
android:label="#string/title_activity_test" >
</activity>
</application></manifest>
You have the line "mGoogleApiClient.connect();" commented out and therefor are not guaranteed to have usable access to the play services WearableAPI
Additionally there are two main reasons why onDataChanged won't be triggered on an android wear device 1) The DataItem you are "putting" hasn't been changed since the last time you put it into the DataLayer. Try adding a timestamp to avoid this issue for debugging purposes. 2) The package name and signature are not identical on the wear apk and mobile apk. Do all you can to ensure these are identical on both modules.
Make sure both the wearable and handheld app modules have the same package name and version number. Also check the applicationId , versionName and versionCode in build.gradle files on both the wearable and handheld app modules of your project if you are building with Gradle.

prevent Android BootReceiver from starting main activity

Here´s my problem:
my Android app registers a boot receiver, which initializes a PushNotification-Manager (PushWoosh).
This is because even after a reboot of the device, the user should be able to receive push notifications without having to start the app manually.
This works, but when the device is rebooted, the apps main activity (MainMenuActivity) is launched and brought to the foreground, which should not happen.
Here´s the involved code:
AndroidManifest.xml:
<!-- Re-register PushManagers after reboot -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar">
<!-- PushWoosh -->
<activity android:name="com.arellomobile.android.push.PushWebview"/>
<activity android:name="com.arellomobile.android.push.MessageActivity"/>
<activity android:name="com.arellomobile.android.push.PushHandlerActivity"/>
<!-- PushWoosh -->
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
<action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
<category android:name="de.myapp.android"/>
</intent-filter>
</receiver>
<!-- PushWoosh -->
<service android:name="com.arellomobile.android.push.PushGCMIntentService"/>
<!-- Boot-Receiever -->
<receiver android:name="de.myapp.android.startup.BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<activity
android:name="de.myapp.android.activity.MainMenuActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<!-- Starten bei Klick auf Launcher Icon -->
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<!-- Starten bei Erhalt einer Push Notification -->
<action android:name="de.myapp.android.MESSAGE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
BootCompleteReceiver.java:
public class BootCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent i) {
PushWooshHelper.setupPushNotifications(context.getApplicationContext());
}
}
PushWooshHelper.java:
public class PushWooshHelper {
public static void setupPushNotifications(Context context) {
PushManager pushManager = new PushManager(context, AppIDs.PUSHWOOSH_APP_ID, AppIDs.GCM_PROJECT_ID);
pushManager.onStartup(context);
pushManager.startTrackingGeoPushes();
}
}
MainMenuActivity.java:
public class MainMenuActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
}
private void checkMessage(Intent intent) {
if (intent != null) {
String log = "PUSH NOTIFICATION RECEIVED.";
if (intent.hasExtra(PushManager.PUSH_RECEIVE_EVENT)) {
log += "message: " + intent.getExtras().getString(PushManager.PUSH_RECEIVE_EVENT);
}
else if (intent.hasExtra(PushManager.REGISTER_EVENT)) {
log += "<register>";
}
else if (intent.hasExtra(PushManager.UNREGISTER_EVENT)) {
log += "<unregister>";
}
else if (intent.hasExtra(PushManager.REGISTER_ERROR_EVENT)) {
log += "<register error>";
}
else if (intent.hasExtra(PushManager.UNREGISTER_ERROR_EVENT)) {
log += "<unregister error>";
}
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
checkMessage(intent);
setIntent(new Intent());
}
}
Please note: I do not have access to PushManager.onStartup(), since it is provided by PushWoosh.
Any help is greatly appreciated!
That's strange. Pushwoosh uses GCM which works after restart of the device out of the box. You just have to register for the push notifications once and then after restart GCM takes care about that itself.

Categories

Resources