Hi I referred Job scheduler from this link. When I want to start a service from the activity button click the service is not started. I had listed the code. Can any one help where I went wrong?
MainActivity
package com.example.samplejobscheduler;
import androidx.appcompat.app.AppCompatActivity;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void scheduleJob(View v) {
ComponentName componentName = new ComponentName(this, MySchedulerService.class);
JobInfo info = new JobInfo.Builder(123, componentName)
.setRequiresCharging(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setPersisted(true)
.setPeriodic(2 * 60 * 1000)
.build();
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled");
} else {
Log.d(TAG, "Job scheduling failed");
}
}
public void cancelJob(View v) {
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
scheduler.cancel(123);
Log.d(TAG, "Job cancelled");
}}
MySchedulerService
public class MySchedulerService extends JobService {
private static final String TAG = "MySchedulerService";
private boolean jobCancelled = false;
#Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job started");
doBackgroundWork(params);
return true;
}
private void doBackgroundWork(final JobParameters params) {
new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 10; i++) {
Log.d(TAG, "run: " + i);
if (jobCancelled) {
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(TAG, "Job finished");
jobFinished(params, false);
}
}).start();
}
#Override
public boolean onStopJob(JobParameters params) {
Log.d(TAG, "Job cancelled before completion");
jobCancelled = true;
return true;
}}
activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="com.example.samplejobscheduler.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="scheduleJob"
android:text="Schedule Job" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="cancelJob"
android:text="Cancel Job" />
</LinearLayout>
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.samplejobscheduler">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"></uses-permission>
<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">
<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=".MySchedulerService"
android:permission="android.permission.BIND_JOB_SERVICE" />
</application>
</manifest>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.1"
defaultConfig {
applicationId "com.example.samplejobscheduler"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
Make sure that the min SDK is 21 or higher.
And in manifest I don't think you need this permission:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"></uses-permission>
After Analysing your code, I will suggest..
.setRequiresCharging(true)
As you have set required charging true, so Service will only run, If your device is in charging, If it not charging, It will not run.
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
As you have set the above condition, then Your service will run only if your device is connected with wifi, If your device is connected with a mobile data connection, service will not run. If you just want service should run only when the internet is available whether be it mobile data or wifi, then set below condition
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
Another thing, you have not added exported flag value to true for the job in the manifest, make it like this below
<service
android:name=".MySchedulerService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE" />
Related
I am having trouble setting up Broadcastreceiver on SMS Receive. I have set all permissions but still it is giving the following permission error
.../system_process W/BroadcastQueue: Permission Denial: receiving
Intent { act=android.provider.Telephony.SMS_RECEIVED flg=0x19000010
(has extras) } to me.jatinsoni.broadcastreceiver/.MyBroadcastReceiver
requires android.permission.RECEIVE_SMS due to sender
com.android.phone (uid 1001)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiver">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<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">
<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=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<category android:name="android.intent.category.APP_MESSAGING"/>
</intent-filter>
</receiver>
</application>
</manifest>
MyBroadcastReceiver
...
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Broadcast Receiver Triggered!", Toast.LENGTH_SHORT).show();
Log.d("BroadcastReceiver", "Broadcast Receiver Triggered!");
}
}
Gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.broadcastreceiver"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
In Android 6 and above defining the permission in the manifest, not enough, you need to ask for the permission at runtime.
You can use this function in your activity class:
final int REQ_PERMISSION_SMS = 1;
private void requestSmsPermission() {
String permission = Manifest.permission.RECEIVE_SMS;
int grant = ContextCompat.checkSelfPermission(this, permission);
if ( grant != PackageManager.PERMISSION_GRANTED) {
String[] permission_list = new String[1];
permission_list[0] = permission;
ActivityCompat.requestPermissions(this, permission_list, REQ_PERMISSION_SMS);
}
}
And also you can add the following callback for the check that, does user allows you to receive SMS or not:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case REQ_PERMISSION_SMS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//user allow you to recieve sms
} else {
//user don't allow you to recieve sms
}
}
}
}
I've made a few apps in the past but none of them have had this issue. It works while debugging in Android Studio, but if I stop debugging and attempt to open the app directly from the phone (after it's already been installed from debugging) I get "[app name]" has stopped working"
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.[HIDDEN].[HIDDEN]">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<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"
android:fullBackupContent="#xml/backup_descriptor">
<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>
<activity
android:name=".WebActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name=".[HIDDEN]FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
Gradle (project)
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
classpath 'com.google.gms:google-services:4.0.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Gradle (app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.[HIDDEN].[HIDDEN]"
minSdkVersion 22
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false // keeps unused methods instead of removing them
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.google.firebase:firebase-messaging:17.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.2'
api 'com.google.android.gms:play-services-gcm:15.0.1'
api 'com.google.firebase:firebase-core:16.0.1'
api 'com.google.firebase:firebase-messaging:17.1.0'
}
apply plugin: 'com.google.gms.google-services'
MainActivity
package com.[HIDDEN].[HIDDEN];
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdReceiver;
import org.json.JSONStringer;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
private Button mOpen_uOrder;
private BottomNavigationView.OnNavigationItemSelectedListener
mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
return true;
case R.id.navigation_notifications:
mTextMessage.setText(R.string.title_notifications);
return true;
}
return false;
}
};
private void mOpen_uOrderClicked() {
Intent intent = new Intent(this, WebActivity.class);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextMessage = (TextView) findViewById(R.id.message);
mOpen_uOrder = (Button) findViewById(R.id.open_uOrder);
mOpen_uOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mOpen_uOrderClicked();
}
});
BottomNavigationView navigation = (BottomNavigationView)
findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
//TODO: Open activity specified in key `click_action`
Log.println(Log.ASSERT, "Click Action: ",
bundle.getString("click_action"));
}
[HIDDEN]FirebaseMessagingService service = new
[HIDDEN]FirebaseMessagingService();
}
}
I had to do it the hard way and commented out everything on MainActivity and then go through line by line uncommenting 1 line, install the apk and then open from my phone to see which line is causing the error, and it was this:
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
//TODO: Open activity specified in key `click_action`
// THE CULPRIT:::Apparently you cannot have log statements in the app when not debugging?
// Because bundle.getString("click_action") works.
Log.println(Log.ASSERT, "Click Action: ", bundle.getString("click_action"));
}
Using Android-7.1.1, SDK-25.3.0
I am having problems with the WiFi-broadcast-receiver. Until Android-7.0.x everything worked well. But now, having updated to Android-7.1.1. with its newest SDK, my WiFi-broadcast-receiver does not return any values anymore.
The List<ScanResult> resultList = wifi.getScanResults(); returns 0 (instead of like before some valuable values). Why is this ??? What could the Android-update have caused or is there any mistake in my code ?? Any help appreciated!
Below is my code:
Setting up the WiFi-broadcast-receiver inside the Fragment (not full fragment but excerts...):
public class ScanTeachingFragment extends Fragment implements MyWifiReceiver.OnWiFiResultListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set up WiFi Manager
this.wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
// register Broadcast-Receiver for WiFi
receiverWifi = new MyWifiReceiver(this.context);
IntentFilter filterWiFi = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
getActivity().registerReceiver(receiverWifi, filterWiFi);
}
// setListener necessary otherwise null-pointer occurs in WiFiReceiver
receiverWifi.setListener(this);
}
private void ScanWifi() {
if (!IndoorNavHelpers.inEmulator()) {
wifiManager.setWifiEnabled(true);
wifiManager.startScan();
}
}
}
Here is the WiFi-broadcast-receiver implementation:
package com.xxxx.yyyy.broadcast_receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import java.util.List;
public class MyWifiReceiver extends BroadcastReceiver {
private Context context;
OnWiFiResultListener resultListener;
// ScanFragment must implement this interface
public interface OnWiFiResultListener {
void scanWiFireceived(List<ScanResult> resultList);
}
// create setListener class (otherwise null-pointer occurs)
public void setListener(OnWiFiResultListener listener) {
this.resultListener = listener;
}
public MyWifiReceiver(Context context)
{
this.context = context;
}
// This method call when number of wifi connections changed
public void onReceive(final Context context, Intent intent) {
WifiManager wifi = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
List<ScanResult> resultList = wifi.getScanResults();
// ???????????????????????????????????????????????????????????
// Here resultList returns 0, WHY ????????????????????????????
// ???????????????????????????????????????????????????????????
// append newly found WiFi-scanResults to WiFiSniffing_File by calling callback-method in MainActivity
if(resultListener != null) {
resultListener.scanWiFireceived(resultList);
}
}
}
Here is my gradle-file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.xxxx.yyyy"
minSdkVersion 25
targetSdkVersion 25
versionCode 1
versionName "0.0.2(26)"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.android.support:support-v4:25.3.0'
compile 'com.android.support:design:25.3.0'
compile files('libs/ftp4j-1.7.2.jar')
compile 'org.greenrobot:eventbus:3.0.0'
compile 'com.github.johnkil.print:print:1.2.2'
compile 'com.github.bmelnychuk:atv:1.2.+'
}
Here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xxxx.yyyy">
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/yyyy_icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:largeHeap="true">
<activity
android:name=".activity.MainActivity"
android:launchMode="singleTop"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:screenOrientation="portrait"
android:excludeFromRecents="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
<action android:name="android.hardware.usb.action.USB_DEVICE_DETATCHED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="#xml/device_filter" />
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" android:resource="#xml/device_filter" />
</activity>
</application>
</manifest>
I finally found a solution: If I factory-reset my Nexus 5X and re-install Android Nougat 7.1.1, then my code works again ! No idea what corrupted the mobile install in the meantime ??? The above code therefore works now !
Turn on your GPS..
For Android 7 the permissions ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION are neccessary to get the Wi-Fi scan results. You also have to turn on location at device.
I am new to this, but trying to get a v simple example working of sending a message from my Wearable to my Phone. I have read other similar questions, but I can't find the solution amongst the answers I have read.
My problem is the onMessageReceived method in my Listener (running on my Mobile) is never called.
I am using real devices, Sony SmartWatch 3 and Samsung S5
What I have working is
My wearable sends the message (using Wearable.MessageApi.sendMessage) and outputs to the log that the message is successfully sent to the correct node.
What I have tried based on other similar questions I have read :-
Package in AndroidManifest is same between Mobile and Wearable
applicationId is same in build.gradle file between Mobile and Wearable
Uninstalling the apps from both Mobile and Wearable and running apps from Android Studio (not in debug mode)
Any guidance very gratefully received, please see my code below.
Thanks
Mobile Code
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.davidson.anothermessagetest" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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=".ListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
</application>
</manifest>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.davidson.anothermessagetest"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
wearApp project(':wear')
compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.google.android.gms:play-services:8.4.0'
}
ListenerService
package com.davidson.anothermessagetest;
import android.util.Log;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.WearableListenerService;
/**
* Created by ddavidson on 09/03/2016.
*/
public class ListenerService extends WearableListenerService {
#Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.v("myTag", "onMessageReceived:");
if (messageEvent.getPath().equals("/message_path")) {
final String message = new String(messageEvent.getData());
Log.v("myTag", "Message path received on watch is: " + messageEvent.getPath());
Log.v("myTag", "Message received on watch is: " + message);
}
else {
super.onMessageReceived(messageEvent);
}
}
#Override
public void onPeerConnected(Node peer) {
Log.v("myTag", "onPeerConnected:");
}
}
Wearable Code
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.davidson.anothermessagetest" >
<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" >
<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" />
</application>
</manifest>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.davidson.anothermessagetest"
minSdkVersion 20
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.android.support:wearable:1.3.0'
compile 'com.google.android.gms:play-services-wearable:8.4.0'
}
MainActivity
package com.davidson.anothermessagetest;
import android.app.Activity;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
public class MainActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient googleClient;
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v("myTag", "Wearable: onCreate");
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);
}
});
// Build a new GoogleApiClient for the Wearable API
googleClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect to the data layer when the Activity starts
#Override
protected void onStart() {
super.onStart();
googleClient.connect();
}
// Send a message when the data layer connection is successful.
#Override
public void onConnected(Bundle connectionHint) {
String message = "Hello wearable\n Via the data layer";
//Requires a new thread to avoid blocking the UI
new SendToDataLayerThread("/message_path", message).start();
}
// Disconnect from the data layer when the Activity stops
#Override
protected void onStop() {
if (null != googleClient && googleClient.isConnected()) {
googleClient.disconnect();
}
super.onStop();
}
// Placeholders for required connection callbacks
#Override
public void onConnectionSuspended(int cause) { }
#Override
public void onConnectionFailed(ConnectionResult connectionResult) { }
public class SendToDataLayerThread extends Thread {
String path;
String message;
// Constructor to send a message to the data layer
SendToDataLayerThread(String p, String msg) {
path = p;
message = msg;
}
public void run() {
NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleClient).await();
for (Node node : nodes.getNodes()) {
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(googleClient, node.getId(), path, message.getBytes()).await();
if (result.getStatus().isSuccess()) {
Log.v("myTag", "Message: {" + message + "} sent to: " + node.getDisplayName());
}
else {
// Log an error
Log.v("myTag", "ERROR: failed to send Message");
}
}
}
}
}
you should add MESSAGE_RECEIVED action into the manifest.xml rather than BIND_LISTENER or DATA_CHANGED (DATA_CHANGED only used for onDataChange), as for high version of gms e.g. 9.6.1
<service android:name=".MyWearService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:scheme="wear" android:host="*"
android:path="/sensor_test" />
</intent-filter>
</service>
Your .ListenerService-declaration in your Mobile-AndroidManifest must be within the <application> tag. In your code it's outside.
Hope this fixes it.
I've upgraded my Nexus 5 to Marshmallow with OTA.
Since the update simple sensor based activity does not work anymore.
The following code do what it should to do on others devices (Galaxy S4 Lolipop, AVD, ...)
Does someone has experiment this too ? Do I miss something ?
Here is the code:
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "fr.rouk1.test"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
package="fr.rouk1"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-feature
android:name="android.hardware.sensor.gyroscope"
android:required="true"/>
<uses-feature
android:name="android.hardware.sensor.accelerometer"
android:required="true"/>
<uses-feature
android:name="android.hardware.sensor.compass"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
</application>
</manifest>
MainActivity.java
package fr.rouk1;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
private TextView mText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView) findViewById(R.id.text);
initSensor();
}
private void initSensor() {
SensorManager sm = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
if (sm.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR) == null) {
sm.registerListener(this,
sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
sm.registerListener(this,
sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
sm.registerListener(this,
sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE),
SensorManager.SENSOR_DELAY_FASTEST);
} else {
sm.registerListener(this,
sm.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
SensorManager.SENSOR_DELAY_FASTEST);
}
}
#Override
public void onSensorChanged(SensorEvent event) {
// this is never called
String s = "";
for (int i = 0; i < event.values.length; i++) {
s = s.concat(String.format("%.4f, ", event.values[i]));
}
mText.setText(s);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
switch (accuracy) {
case SensorManager.SENSOR_STATUS_ACCURACY_HIGH:
Log.d("rouk1", "SENSOR_STATUS_ACCURACY_HIGH");
break;
case SensorManager.SENSOR_STATUS_ACCURACY_LOW:
Log.d("rouk1", "SENSOR_STATUS_ACCURACY_LOW");
break;
case SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM:
Log.d("rouk1", "SENSOR_STATUS_ACCURACY_MEDIUM");
break;
case SensorManager.SENSOR_STATUS_NO_CONTACT:
Log.d("rouk1", "SENSOR_STATUS_NO_CONTACT");
break;
case SensorManager.SENSOR_STATUS_UNRELIABLE:
Log.d("rouk1", "SENSOR_STATUS_UNRELIABLE");
break;
}
}
}
Finally found this issue.
Temporary solution is to use SENSOR_DELAY_GAME instead of SENSOR_DELAY_FASTEST.