Android Wear not receiving OnDataChanged call - java

I have read any thread that is on this topic in the last 2 days.. but I still cannot figure out what is wrong with my code.
I have Mobile and Wear app. the mobile has only widget and widgetconfig activities (no main activity).
Here is the mobile app files:
AndroidManifest: (simple appwidget and appwidget_config activities)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.xx.yy.remotedoor">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/housek"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".DoorConf"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
<receiver android:name=".upDoor">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/up_door_info" />
</receiver>
</application>
</manifest>
upDoor.java: (Look at send_to_wear function)
package net.xx.yy.remotedoor;
import ...
public class upDoor extends AppWidgetProvider {
public static String TAG = "Remote door GAPI";
public static String CLICK_DOOR = "ClickDoorOpen";
public static String DOOR_ID = "DoorID";
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
CharSequence widgetText = "Test";
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.up_door_widget);
views.setTextViewText(R.id.textView, widgetText);
Intent intent = new Intent(context, upDoor.class);
intent.setAction(CLICK_DOOR);
intent.putExtra(DOOR_ID, Integer.toString(appWidgetId));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.houseIcon, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
send_to_wear(context);
}
}
private static void send_to_wear(Context context) {
// Sending data to wear
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected: " + connectionHint);
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d(TAG, "onConnectionFailed: " + result);
}
})
.addApi(Wearable.API)
.build();
Log.w("Google API", "Connecting");
mGoogleApiClient.connect();
Log.w("Google API", Boolean.toString(mGoogleApiClient.isConnected()));
PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/doors/1");
putDataMapReq.getDataMap().putString("caption", "test"); putDataMapReq.getDataMap().putLong("Time",System.currentTimeMillis());
putDataMapReq.setUrgent();
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
com.google.android.gms.common.api.ResultCallback<DataApi.DataItemResult> send_callback =
new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(#NonNull DataApi.DataItemResult result) {
if (!result.getStatus().isSuccess()) {
Log.w("Result", "Failed");
}else{
Log.w("Result", "Success");
}
Log.w("Item", result.getDataItem().getUri().toString());
Log.w("Reason", result.getStatus().getStatusMessage());
}
};
com.google.android.gms.common.api.PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
pendingResult.setResultCallback(send_callback);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
#Override
public void onEnabled(Context context) {...}
#Override
public void onDisabled(Context context) {...}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(CLICK_DOOR)) {
send_to_wear(context);
}
}
}
On the Wear side:
Manifest: (I configured it at same package name, is that ok?)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.xx.yy.remotedoor">
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="#drawable/housek"
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=".main"
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=".dataLayer" android:exported="false" 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="*" android:pathPrefix="*" />
</intent-filter>
</service>
</application>
</manifest>
and the dataLayer java part:
package net.xx.yy.remotedoor;
import ...
public class dataLayer extends WearableListenerService { //implements DataApi.DataListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LOG";
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.w(TAG, "Wear got on_change");
final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
// Do I need it??
ConnectionResult connectionResult = googleApiClient.blockingConnect(30, TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Log.e(TAG, "Failed to connect to GoogleApiClient.");
return;
}
for (DataEvent dataEvent : events) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
DataItem item = dataEvent.getDataItem();
Log.w(TAG, "item path: " + item.getUri().getPath());
if(item.getUri().getPath().startsWith("/doors/")){
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
// Do something
}
}
}
}
}
On the mobile log I can see:
DataItemResult : Success
Item: wear://HOST_ID/doors/1
On the wear log I cannot see anything related to this..
What am I doing wrong!?
Thanks!!

Related

Monitoring received SMS within a service

I'm trying to create a service that monitors received sms,
the service onStartCommand and OnCreate are getting called, however when I'm sending sms Broadcast receiver OnReceive is not getting called, What is the problem?
Here is my code:
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">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<service android:enabled="true" android:name="com.example.myapplication.SmsServices" />
<receiver android:name=".SmsListener"
android:exported="true" android:priority="1000">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
Service
public class SmsServices extends Service {
private SmsListener smslistener;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("SmsServices", "onStartCommand");
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
smslistener = new SmsListener();
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smslistener, filter);
Log.d("SmsServices", "Registered Sms Listener.");
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(smslistener);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Broadcast receiver
public class SmsListener extends BroadcastReceiver {
public SmsListener (){}
#Override
public void onReceive(Context context, Intent intent) {
Log.d("SmsListener", "Sms received.");
if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
String msgBody = smsMessage.getMessageBody();
String msgAddr = smsMessage.getOriginatingAddress();
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent( this, SmsServices.class ) );
Log.d("Main","Service Started.");
}
}

Service doesnt work correctly in Background

I am making Music Player which downloads music from Firebase.
Its working fine but I cannot play music in background.
It works for like 1.5 minute (after locking screen) and it stops.
In logs after I lock screen it says "Inactivity, disconnecting from Service".
I think this may be main problem here.
Here code :
Fragment of Playing Music:
public class PlayerFragment extends Fragment {
private FirebaseStorage storage;
private ImageButton main_btn, next_btn, back_btn, fav_btn, settings_btn;
private Uri localSong;
private Intent myService;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_player, container, false);
storage = FirebaseStorage.getInstance();
main_btn= view.findViewById(R.id.player_main_btn);
next_btn= view.findViewById(R.id.player_next_btn);
back_btn= view.findViewById(R.id.player_back_btn);
fav_btn = view.findViewById(R.id.player_song_fav_btn);
settings_btn = view.findViewById(R.id.player_song_options_btn);
storage.getReference().child("songs/ni_bien_ni_mal.mp3").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
localSong=uri;
}
});
MainActivity mainActivity = (MainActivity) getActivity();
myService = new Intent(getActivity(), BackgroundSoundService.class);
main_btn.setOnClickListener(v -> {
if( main_btn.getDrawable().getConstantState().equals( main_btn.getContext().getDrawable(R.drawable.ic_play).getConstantState()))
{
new Thread(new Runnable() {
#Override
public void run() {
myService.putExtra("uri",localSong.toString() );
mainActivity.startService(myService);
}
}).start();
main_btn.setImageResource(R.drawable.ic_pause);
}
else
{
new Thread(new Runnable() {
#Override
public void run() {
// mainActivity.stopService(myService);
main_btn.setImageResource(R.drawable.ic_play);
}
}).start();
}
});
fav_btn.setOnClickListener(v->{
if( fav_btn.getDrawable().getConstantState().equals( fav_btn.getContext().getDrawable(R.drawable.ic_heart_empty).getConstantState()))
{
fav_btn.setImageResource(R.drawable.ic_heart_full);
}else{
fav_btn.setImageResource(R.drawable.ic_heart_empty);
}
});
return view;
}
}
Manifest: ( Service declaration is at bottom)
<?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.company.altasnotas">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
<application
android:allowBackup="true"
android:icon="#drawable/altas_notes"
android:label="#string/app_name"
android:roundIcon="#drawable/altas_notes"
android:supportsRtl="true"
android:testOnly="false"
android:theme="#style/Theme.AltasNotas">
<activity
android:name=".IntroActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AltasNotas.NoActionBar"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"
tools:replace="android:value" />
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
</activity>
<service android:enabled="true" android:name=".BackgroundSoundService" />
</application>
</manifest>
Service :
public class BackgroundSoundService extends Service {
String song_string;
int x;
private static final String TAG = "BackgroundSoundService";
MediaPlayer player;
public IBinder onBind(Intent arg0) {
Log.i(TAG, "onBind()" );
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
public int onStartCommand(Intent intent, int flags, int startId) {
song_string= intent.getStringExtra("uri");
if (song_string != null) {
System.out.println("Song string : " + song_string);
player = MediaPlayer.create(this, Uri.parse(song_string));
player.setLooping(false); // Set looping
player.setVolume(0.5f, 0.5f);
if (!(String.valueOf(x) == null || String.valueOf(x).isEmpty())) {
player.seekTo(x);
}
player.start();
}
return Service.START_STICKY;
}
public IBinder onUnBind(Intent arg0) {
Log.i(TAG, "onUnBind()");
return null;
}
public void onStop() {
Log.i(TAG, "onStop()");
}
public void onPause() {
Log.i(TAG, "onPause()");
x=player.getCurrentPosition();
player.pause();
}
#Override
public void onDestroy() {
if(player!=null) {
player.stop();
player.reset();
player.release();
Log.i(TAG, "onCreate() , service stopped...");
}
}
#Override
public void onLowMemory() {
Log.i(TAG, "onLowMemory()");
}
}
Despite Sticky and declaration in Manifest , it still doesnt work in background. Also I want to add pause button and I dont know exacly how can I do that.

A service is not communicating with activity

I'm creating a service which is started, but no communication is received via broadcast. I suspected that there was something wrong with IntentFilter and names, but it all seems correct.
I've been studying example from vogella (par. 8)
What have I done wrong? Why broadcast is not received by MainActivity?
MainActivity
package com.jackslastssid;
import ...
public class MainActivity extends ActionBarActivity {
class MainActivityAfterCaller extends AfterCaller {
public void callback() {
update_something();
}
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(MainActivity.this, "Daemon called back! :)", Toast.LENGTH_LONG).show(); // never happend
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(SayHelloDaemon.NOTIFICATION));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
}
SayHelloDaemon:
public class SayHelloDaemon extends IntentService {
public static final String NOTIFICATION = "com.jackslastssid.SayHelloDaemon";
public SayHelloDaemon() {
super("SayHelloDaemon");
}
class SayHelloDaemonAfterCaller extends AfterCaller {
public void callback() {
Intent intent = new Intent(NOTIFICATION);
sendBroadcast(intent);
}
}
// will be called asynchronously by Android
#Override
protected void onHandleIntent(Intent intent) {
new SayHelloAsyncTask().execute(new Pair<AfterCaller, Map>(new SayHelloDaemonAfterCaller(), Data.getInstance().getQueryMap()));
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jackslastssid" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<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>
<service
android:name=".SayHelloDaemon"
android:icon="#drawable/icon"
android:label="#string/service_name"
android:exported="false"/>
</application>
</manifest>
It looks like you haven't started the service in the activity.
Intent intent = new Intent(this, SayHelloDaemon.class);
startService(intent);

Try to resolve ActivityNotFoundException

I try to share a post on google+ but I obtain this Exception. The Activity that creates the Exception is ExampleActivity and this is its code:
public class ExampleActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = "ExampleActivity";
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
#Override//onCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
mPlusClient = new PlusClient.Builder(this, this, this)
.setVisibleActivities("http://schemas.google.com/AddActivity","http://schemas.google.com/BuyActivity")
.build();
// Progress bar to be displayed if the connection failure is not resolved.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
Button shareButton = (Button) findViewById(R.id.share_button);
shareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Launch the Google+ share dialog with attribution to your app.
Intent shareIntent = new PlusShare.Builder()
.setType("text/plain")
.setText("Welcome to
the Google+ platform.")
.setContentUrl(Uri.parse("https://developers.google.com/+/"))
.getIntent();
startActivityForResult(shareIntent, 0);
}
});
}
#Override//onStart
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
#Override//onStop
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override// onConnectionFailed
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the result and resolve the connection failure upon a user click.
mConnectionResult = result;
}
#Override //onActivityResult
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
// #Override
// public void onConnected(Bundle connectionHint) {
// String accountName = mPlusClient.getAccountName();
// Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
// }
#Override //onDisconnected
public void onDisconnected() {
String accountName = mPlusClient.getAccountName();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
}
#Override//onConnected
public void onConnected() {
// TODO Auto-generated method stub
}
#Override
public void onClick(View arg0) {
}
}
This is the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.applicazionescienza"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.applicazionescienza.Menu"
android:label="#string/app_name"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.applicazionescienza.Informazioni"
android:label="#string/title_activity_informazioni" >
</activity>
<activity
android:name="com.example.applicazionescienza.Regolamento"
android:label="#string/title_activity_regolamento" >
</activity>
<activity
android:name="com.example.applicazionescienza.Gioca"
android:label="#string/title_activity_gioca" >
</activity>
<activity
android:name="com.example.applicazionescienza.Livello"
android:label="#string/title_activity_livello" >
</activity>
<activity
android:name="com.example.applicazionescienza.Punteggio"
android:label="#string/title_activity_punteggio" >
</activity>
<activity
android:name="com.example.applicazionescienza.TwitterActivity"
android:label="#string/title_activity_twitter"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="casa"
android:scheme="app" />
</intent-filter>
</activity>
<activity
android:name="com.example.applicazionescienza.FacebookActivity"
android:label="#string/title_activity_facebook" >
</activity>
<activity
android:name="com.example.applicazionescienza.ExampleActivity"
android:label="#string/title_activity_example" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
The Exception say: No activity found to handle Intent(act=android.intent.action.SEND....
Someone can help me?
Try and clean the project, uninstall your app from device and reinstall.

onReceive never getting called

Below is my Java code and my XML code. Can someone please tell me why my onReceieve method is never getting called.
Java:
public class PopUPSMS extends Activity {
String RECEIVE_SMS = "RECEIVE_SMS";
private static final String LOG_TAG = "PopUPSMS";
static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(LOG_TAG, "onCreate");
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(LOG_TAG, "onReceive");
}
}, new IntentFilter(RECEIVE_SMS));
}
}
XML:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.smith.johnathan.phone"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".PopUPSMS"
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>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-sdk android:minSdkVersion="3" />
</manifest>
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(LOG_TAG, "onReceive");
}
}, new IntentFilter(RECEIVE_SMS));
You have registered your broadcast receiver with the string "RECEIVE_SMS". The IntentFilter should be of a form of an action. With your declaration:
static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
you will have:
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(LOG_TAG, "onReceive");
}
}, new IntentFilter(ACTION));
You can have a look at the Api demos Manifest for the XML declaration
You can't use receiver as an inner class. Create a separate one.
Don't you need to specify that you want to receive SMS in your manifest?
<application android:icon="#drawable/icon" android:label="#string/app_name">
<receiver android:name=".MyApp">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>

Categories