Android Broadcast Receiver is showing permission error even it is set - android

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
}
}
}
}

Related

Fire base onMessageReceived isn't working at all

I've looked over all the answers I could find, the particular function of code isn't working even in foreground. I tried changing the manifest, changing the code, all i get in the logger are these 2 of these things:
D/FA: Logging event (FE): notification_receive(_nr), ...
This is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/avatar"
android:label="#string/app_name"
android:roundIcon="#drawable/avatar"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".StartActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"/>
<service android:name=".GettingDeviceTokenService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".NotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
And here is the notification service:
public class NotificationService extends FirebaseMessagingService {
public static int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "1";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("+++", remoteMessage.toString());
if (remoteMessage.getData().size() > 0) {
Log.d("dataa", "Data Payload: " + remoteMessage.getData().toString());
}
}
This is the app gradle file
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.example.xghos.Wrenchy"
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'net.hockeyapp.android:HockeySDK:5.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'
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.google.firebase:firebase-core:16.0.1'
implementation 'com.google.firebase:firebase-messaging:17.3.0'
implementation 'com.ethanhua:skeleton:1.1.1'
implementation 'io.supercharge:shimmerlayout:2.1.0'
implementation "com.daimajia.swipelayout:library:1.2.0#aar"
}
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '26.1.0'
}
}
}
}
apply plugin: 'com.google.gms.google-services'
and the GettingDeviceTokenService:
package com.example.xghos.Wrenchy;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class GettingDeviceTokenService extends FirebaseMessagingService {
#Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.d("DeviceToken ==> ", s);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
}
}
EDIT: the problem was solved by changing the intent filter of the GettingDeviceTokenService from
<action android:name="com.google.firebase.MESSAGING_EVENT" />
to
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
You should consider difference between data message and display message.
Display message has payload with key notification and are automatically displayed when app is in background and also call onMessageReceived() if app is already in foreground.
Data message has payload key data . They always invoke onMessageReceived()
You have registered NotificationService service in your manifest. Since latest update for firebase notifications, the same service will handle new token and received messages. In your case you should register in manifest only GettingDeviceTokenService because you override both methods and remove NotificationService.
Try this way. It worked for me Perfectly.
1. Create a Service
public class YourService extends FirebaseMessagingService {
public static int NOTIFICATION_ID = 1;
#Override
public void onNewToken(String s) {
super.onNewToken(s);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this, "2")
.setSmallIcon(R.drawable.your_icon)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (NOTIFICATION_ID > 1073741824) {
NOTIFICATION_ID = 0;
}
Objects.requireNonNull(notificationManager).notify(NOTIFICATION_ID++, mNotifyBuilder.build());
}
}
Now add this to Manifest
<service
android:name=".YourService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>

SugarORM NullPointerException on save() method

I need a database in my app and I chose SugarORM. But I can't even run a simple example. I have NullPointerException when I use save() method.
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.aleksandr.birukov.myapplication"
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
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'
compile 'com.android.support:support-annotations:27.1.1'
compile 'com.github.satyan:sugar:1.4'
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aleksandr.birukov.myapplication">
<application
android:allowBackup="true"
android:name="com.orm.SugarApp"
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>
<meta-data
android:name="DATABASE"
android:value="notes.db" />
<meta-data
android:name="VERSION"
android:value="1" />
<meta-data
android:name="QUERY_LOG"
android:value="true" />
<meta-data
android:name="DOMAIN_PACKAGE_NAME"
android:value="com.aleksandr.birukov.myapplication" />
</application>
</manifest>
Note.java
package com.aleksandr.birukov.myapplication;
import com.orm.SugarRecord;
public class Note extends SugarRecord {
String title, note;
long time;
public Note() {
}
public Note(String title, String note, long time) {
this.title = title;
this.note = note;
this.time = time;
}
}
MainActivity.java
package com.aleksandr.birukov.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Note note = new Note("title", "desc", 100);
note.save();
}
}
I don't understand what I did wrong?
Make your class extend SugarRecord< Note >

WiFi broadcast receiver not delivering in Android 7.1.1

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.

onMessageReceived not called on Mobile

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.

Receive sms broadcast on KitKat

I really tried it all, the broadcast receiver doesn't receive new incoming sms broadcasts.
I'm running on my phone 4.4.4, I just want to listen to incoming messages, that is.
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name=".SmsReceiver"
android:enabled="true"
>
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED_ACTION" />
</intent-filter>
</receiver>
</application>
the broadcast receiver:
public class SmsReceiver extends BroadcastReceiver {
public SmsReceiver() {}
#Override
public void onReceive(Context context, Intent intent) {
Log.d("v", "SMS onReceive");
}
gradle:
android {
compileSdkVersion 20
buildToolsVersion "21.0.0"
defaultConfig {
applicationId "com.dev.xxx"
minSdkVersion 19
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:+'
}
The <action> you've defined in the <receiver>'s <intent-filter> in the manifest is incorrect. It should be:
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
You might be confusing it with the class constant String identifier android.provider.Telephony.Sms.Intents.SMS_RECEIVED_ACTION, which has the value shown above.

Categories

Resources