BroadcastReceiver not responding - java

I have a receiver that is called whenever an SMS is received
public class SMSReceiver extends BroadcastReceiver {
private SharedPreferences prefs;
private String prefName = "MyPref";
private static final String NUMBER_KEY = "number";
#Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
String Sender = null;
if (bundle != null) {
// ---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
Sender = msgs[i].getOriginatingAddress();
}
prefs = context
.getSharedPreferences(prefName, Context.MODE_PRIVATE);
String phoneNumber = (String) prefs.getString(NUMBER_KEY, "");
// If the sender of the SMS just received is the same as one chosen
// earlier
if (Sender.equals(phoneNumber)) {
Toast.makeText(context, "text message received",
Toast.LENGTH_LONG).show();
// ---Launch the minderActivity even when the app is not in the
// foreground---
Intent minderActivityIntent = new Intent(context, Minder.class);
minderActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(minderActivityIntent);
// ---send a broadcast intent to update the SMS received in the
// activity---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("Sender", Sender);
context.sendBroadcast(broadcastIntent);
}
}
}
}
I register the receiver in an activity called "minder" using a button
registerReceiver(intentReceiver, intentFilter);
In this "minder" activity I also have a BroadcastReceiver
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// ---gather up all the necessary user input---
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
final Button btn2 = (Button) findViewById(R.id.btnContacts);
String phoneNumber = (String) prefs.getString(NUMBER_KEY, "");
String messageChosen = (String) prefs.getString(MESSAGE_KEY, "");
String delay = (String) prefs.getString(DELAY_KEY, "");
String Sender = (String) intent.getExtras().getString("Sender");
if (Sender.equals(phoneNumber)) {
sendSMS(phoneNumber, messageChosen, delay);
}
}
};
All of the permissions are defined in the manifest.
Unfortunately when I test the receiver (i.e. send an sms to the phone, after the receiver has been registered, from the number that is defined as "phoneNumber") the app performs no action. Any ideas what is missing from my above code?

Related

How do I pass information between BroadcastReceiver and main method

In a SMS aplication I want to pass a value of a String from de BroadcastReceiver to the main method.
public class LucesAlarma extends AppCompatActivity {
IntentFilter intentFilterLA;
private BroadcastReceiver intentRecieverLA = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
final String MENSAJE = intent.getExtras().getString("mensaje");
String NUMERODELMENSAJE = intent.getExtras().getString("numero");
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_luces_alarma);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
intentFilterLA = new IntentFilter();
intentFilterLA.addAction("SMS_RECEIVED_ACTION");
//I want to use the String Mensaje from the BroadcastReceiver here
}
#Override
protected void onResume()
{
registerReceiver(intentRecieverLA, intentFilterLA);
super.onResume();
}
#Override
protected void onPause()
{
unregisterReceiver(intentRecieverLA);
super.onPause();
}
}
Here is the SMS receiver code
public class ReceptorSMS extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
SmsMessage[]messages=null;
String str = "";
String num = "";
String men = "";
if(bundle != null)
{
Object[] pdus = (Object[]) bundle.get("pdus");
assert pdus != null;
messages = new SmsMessage[pdus.length];
for (int i=0 ; i<messages.length;i++)
{
messages[i]=SmsMessage.createFromPdu((byte[])pdus[i]);
num = messages[i].getDisplayOriginatingAddress();
str += "Mensaje de" +messages[i].getOriginatingAddress();
str += ":";
str += messages[i].getMessageBody();
str += "\n";
men = messages[i].getMessageBody();
}
// Toast.makeText(context,str,Toast.LENGTH_SHORT).show();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
broadcastIntent.putExtra("mensaje", men);
broadcastIntent.putExtra("numero", num);
context.sendBroadcast(broadcastIntent);
}
}
}
Please I want to know how to get that String into the main methot.
I assume that you want to start activity when receive any SMS, than you should do like this
in your ReceptorSMS class
public void onReceive(Context context, Intent intent)
{.
.
.
Toast.makeText(context,str,Toast.LENGTH_SHORT).show();
Intent broadcastIntent = new Intent();
broadcastIntent .setClassName("<YOUR PACKAGE NAME>", "<YOUR PACKAGE NAME>.LucesAlarma");
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
broadcastIntent.putExtra("mensaje", men);
broadcastIntent.putExtra("numero", num);
context.startActivity(broadcastIntent);
}
after that in onCreate
Intent intent = getIntent();
String sms= intent.getStringExtra("sms");
String men = intent.getStringExtra("mensaje");
String num = intent.getStringExtra("numero");

Android: send sms after receiving one

I' writing an app to send phone location after receiving an SMS request. Receiving SMS's works and sending SMS works too. What to do to make it send SMS after receiving one?
MainActivity
final static String gpsLocationProvider = LocationManager.GPS_PROVIDER;
final static String networkLocationProvider = LocationManager.NETWORK_PROVIDER;
static String loc;
public LocationManager locationManager;
static TextView messageBox;
public void sendSMS(String phoneNumber, String message)
{
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageBox = (TextView)findViewById(R.id.messageBox);
locationManager =
(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLocation_byGps =
locationManager.getLastKnownLocation(gpsLocationProvider);
Location lastKnownLocation_byNetwork =
locationManager.getLastKnownLocation(networkLocationProvider);
if (lastKnownLocation_byGps != null) {
loc = "gps " + lastKnownLocation_byGps.getLatitude();
}
if (lastKnownLocation_byNetwork != null) {
loc = "net lat:" + lastKnownLocation_byNetwork.getLatitude() + " long:" + lastKnownLocation_byNetwork.getLongitude();
}
}
public static void updateMessageBox(String msg) {
messageBox.setText(msg);
}
Receiver
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle=intent.getExtras();
Object[] messages=(Object[])bundle.get("pdus");
SmsMessage[] sms=new SmsMessage[messages.length];
for(int n=0;n<messages.length;n++){
sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(SmsMessage msg:sms){
MainActivity.updateMessageBox("\nFrom: "+msg.getOriginatingAddress()+"\n"+
"Message: "+msg.getMessageBody());
}
}
Where to put sendSMS method to send SMS after receiving one?
You can call your send sms code statements at the end of onReceive method, because this method executes when you receive a sms.

Passing data from BroadCastRecevier to activity

I have an SMS reader application and i am showing the senderno and message body into the Custom Listview. For the incoming messages i have registered a broadcast receiver and populating the listView.
Whenever a new message is coming in the broadcast Receiver i am able to get it but I want to this data to be passed onto the activity.
The code snippets are :
MainActvity.java
public class MainSmsActivity extends Activity{
private ListView smsList;
SmsAdapter smsAdapter;
private SmsDao smsDao;
private List<SmsDao> smsDataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_demo);
smsDataList = new ArrayList<SmsDao>();
Intent intent = new Intent();
intent.setAction("com.mobile.sms.IncomingSms");
sendBroadcast(intent);
populateSms();
}
public void populateSms(){
Uri inboxURI = Uri.parse("content://sms/inbox");
String[] reqCols = new String[] { "_id", "address", "body", "date" };
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(inboxURI, reqCols, null, null, null);
smsDataList.clear();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
smsDao = new SmsDao();
smsDao.setMessageBody(cursor.getString(1));
smsDao.setSenderNo(cursor.getString(2));
smsDao.setMessageTime(cursor.getLong(3));
smsDataList.add(smsDao);
}
smsAdapter = new SmsAdapter(this,smsDataList);
smsList.setAdapter(smsAdapter);
smsAdapter.notifyDataSetChanged();
cursor.close();
}
}
IncomingSms.Java
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
int duration = Toast.LENGTH_LONG; // HERE I WANT TO SEND MESSAGE BODY TO THE MAIN ACTIVITY CLASS
Toast toast = Toast.makeText(context,
"senderNum: " + senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
I am able to receive all the messages intially into the list view but I want that the ListView should get automatically updated as soon as new message arrives.
In your broadcasereceiver do something like this: (use that intent)
public class SMSReceiver extends BroadcastReceiver {
public static final String NOTIFICATION = "receiver_sms";
#Override
public void onReceive(Context context, Intent intent) {
Log.i("onReceive methode", "new SMS Comming");
Bundle myBundle = intent.getExtras();
SmsMessage[] messages = null;
String strMessage = "", address = "";
abortBroadcast();
if (myBundle != null) {
// get message in pdus format(protocol description unit)
Object[] pdus = (Object[]) myBundle.get("pdus");
// create an array of messages
messages = new SmsMessage[pdus.length];
Log.i("onReceive methode", "new SMS Comming");
for (int i = 0; i < messages.length; i++) {
// Create an SmsMessage from a raw PDU.
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// get the originating address (sender) of this SMS message in
// String form or null if unavailable
address = messages[i].getOriginatingAddress();
// get the message body as a String, if it exists and is text
// based.
strMessage += messages[i].getMessageBody();
strMessage += "\n";
}
// show message in a Toast
}
// this is what you need
Intent broadcast = new Intent(NOTIFICATION);
broadcast.putExtra("data", strMessage);
LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast);
}
and then register ur receiver in ur activity
public BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(tag, "SMS Received.");
// Intent i = getIntent();
Bundle b = intent.getBundleExtra("SMS");
// String bun = b.getString("MyData");
Log.i(tag, "Bundle: " + b);
String str = intent.getStringExtra("data");
parseSMSData(str);
}
};
and then in onResume():
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter(SMSReceiver.NOTIFICATION));
}
and in onDestroy() you must unregister that receiver like this:
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onDestroy();
}
and also don't forget to add this in ur manifest file in application tag:
<receiver android:name=".SMSBroadcastReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
register your service in OnResume() then you can access easily within your class,
#Override
public void onResume()
{
super.onResume();
this.registerReceiver(this.yourservice, new IntentFilter("your service type"));
}
and unregister the service in your onpause()
#Override
public void onPause() {
super.onPause();
try
{
this.unregisterReceiver(this.your service);
}
catch(Exception e)
{
e.printStackTrace();
}
}
add the your broadcast receiver in your activity ,
private WakefulBroadcastReceiver IncomingSms = new WakefulBroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//use your receiver content
}
Put the following class in your MainSmsActivity so that you should be able to process your list.
private class IncomingSms extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("incomingSms")) {
//your impl here
}
}
}
and in onCreate() of your MainSmsActivity activity, place the following code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
IncomingSms broadcastReceiver = new IncomingSms(); // declare it outside so that it should be accessible in onDestroy()
IntentFilter intentFilter = new IntentFilter("incomingSms");
registerReceiver(broadcastReceiver , intentFilter);
}
and in onDestroy() place the following code
#Override
protected void onDestroy() {
if (broadcastReceiver != null) {
unregisterReceiver(broadcastReceiver);
}
super.onDestroy();
}

I can't refresh my webview when I open push notification

I want to create Android app of my web site using WebView and gcm, I am about to finish my project. My application can receive push notifications, WebView is working properly but I have a problem. The problem is that I can't refresh my WebView when I open push notification. When the app is on background mood it can't be refreshed. It shows old view.
My MainActivity.java:
public class MainActivity extends Activity {
// label to display gcm messages
TextView lblMessage;
Controller aController;
private WebView webView;
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
private Intent notificationIntent;
public static String name;
public static String email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get webview
webView = (WebView) findViewById(R.id.webView1);
startWebView("http://admob.adnet.az/main/index.php");
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
aController = (Controller) getApplicationContext();
// Check if Internet present
if (!aController.isConnectingToInternet()) {
// Internet Connection is not present
aController.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to Internet connection", false);
// stop executing code by return
return;
}
// Getting name, email from intent
Intent i = getIntent();
name = i.getStringExtra("name");
email = i.getStringExtra("email");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest permissions was properly set
GCMRegistrar.checkManifest(this);
lblMessage = (TextView) findViewById(R.id.lblMessage);
// Register custom Broadcast receiver to show messages on activity
registerReceiver(mHandleMessageReceiver, new IntentFilter(
Config.DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
final String email = i.getStringExtra("email");
// Check if regid already presents
if (regId.equals("")) {
// Register with GCM
GCMRegistrar.register(this, Config.GOOGLE_SENDER_ID);
} else {
// Device is already registered on GCM Server
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(), "Already registered with GCM Server", Toast.LENGTH_LONG).show();
String url = "http://admob.adnet.az/main/index.php?email="+email+"&regid="+regId;
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
//Show loader on url load
// public void onLoadResource (WebView view, String url) {
// if (progressDialog == null) {
// in standard case YourActivity.this
// progressDialog = new ProgressDialog(ShowWebView.this);
// progressDialog.setMessage("Loading...");
// progressDialog.show();
// }
// }
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
/*
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
*/
/*
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
*/
//Load url in webview
webView.loadUrl(url);
//new ReloadWebView(this, 5, webView);
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
aController.register(context, name, email, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
// execute AsyncTask
mRegisterTask.execute(null, null, null);
}
}
}
private void post(String serverUrl, Map<String, String> params) {
// TODO Auto-generated method stub
}
private void startWebView(String string) {
// TODO Auto-generated method stub
}
// Create a broadcast receiver to get message and show on screen
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(Config.EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
aController.acquireWakeLock(getApplicationContext());
// Display message on the screen
lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "Got Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
aController.releaseWakeLock();
}
};
#Override
protected void onDestroy() {
// Cancel AsyncTask
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
// Unregister Broadcast Receiver
unregisterReceiver(mHandleMessageReceiver);
//Clear internal resources.
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
}
super.onDestroy();
}
}
My GCMIntentService.java:
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
private Controller aController = null;
public GCMIntentService() {
// Call extended class Constructor GCMBaseIntentService
super(Config.GOOGLE_SENDER_ID);
}
/**
* Method called on device registered
**/
#Override
protected void onRegistered(Context context, String registrationId) {
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Device registered: regId = " + registrationId);
aController.displayMessageOnScreen(context, "Your device registred with GCM");
Log.d("NAME", MainActivity.name);
aController.register(context, MainActivity.name, MainActivity.email, registrationId);
}
/**
* Method called on device unregistred
* */
#Override
protected void onUnregistered(Context context, String registrationId) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Device unregistered");
aController.displayMessageOnScreen(context, getString(R.string.gcm_unregistered));
aController.unregister(context, registrationId);
}
/**
* Method called on Receiving a new message from GCM server
* */
#Override
protected void onMessage(Context context, Intent intent) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("price");
aController.displayMessageOnScreen(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on receiving a deleted message
* */
#Override
protected void onDeletedMessages(Context context, int total) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
aController.displayMessageOnScreen(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on Error
* */
#Override
public void onError(Context context, String errorId) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received error: " + errorId);
aController.displayMessageOnScreen(context, getString(R.string.gcm_error, errorId));
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
if(aController == null)
aController = (Controller) getApplicationContext();
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
aController.displayMessageOnScreen(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Create a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
Thanks in Advance
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
** notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); **
PendingIntent intent =PendingIntent.getActivity(context, 0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
OR Add in manifest
<activity
android:name = "MainActivity"
android:noHistory="true"
android:launchMode = "singleTop"/>

How do i set a listener in an activity from another class?

I am working on an application that needs to read an incoming message. Now, i found out that i need to use the onReceive method from the BroadcastReceiver class. Now i got to know that java does not allow extending two classes, so how do i get it working, i have been stuck on this from a long time, please help! Also if there is some other way to do this, please do quote.
public class SMS extends Activity {
Button btnSendSMS;
EditText txtPhoneNo;
EditText txtMessage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sms);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String phoneNo = txtPhoneNo.getText().toString();
if (phoneNo.length()>0)
sendSMS(phoneNo, phoneNo);
else
Toast.makeText(getBaseContext(),
"Please enter a valid Phone Number.",
Toast.LENGTH_SHORT).show();
}
});
}
private void sendSMS(String phoneNumber, String message)
{
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, SMS.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
}
Context context = getApplicationContext();
Intent intent = new Intent();
object.onReceive(context, intent); }
class SMSBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SMSBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());
Toast.makeText(context, "HI", Toast.LENGTH_SHORT).show();
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
if (messages.length > -1) {
Toast.makeText(context, "Message recieved: " + messages[0].getMessageBody(), 7000).show();
}
}
}
} }
You don't need to extend two classes (which is not possible and never required in java) to achieve your goal. For getting the last message simply create a static message variable, lets say in your SMSBroadcastReceiver and set that variable to latest message received in onreceive. This static variable can be accessed throughout your app using SmsReceiver.latestmessage

Categories

Resources