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");
Related
i need to start a service whenever the user wants, its the same service with only different input data. I tried with workmanager and using threads libraries, its important to say that is a long running task. Down below is my code
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startThread(View view){
Value1 = findViewById(R.id.Value1);
Value2 = findViewById(R.id.Value2);
String value1 = Value1.getText().toString();
String Value2 = Value2.getText().toString();
Intent service = new Intent(this, servicio.class);
service.putExtra("value1", value1);
service.putExtra("value2", value2);
startService(service);
service file
public class servicio extends Service {
private static final String TAG = "service";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String rapida = intent.getStringExtra("value1");
String lenta = intent.getStringExtra("value2");
int value = Integer.parseInt(rapida);
int to = Integer.parseInt(lenta);
for (int i = value; i<to; i++){
Log.d(TAG, "number: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Intent notificationintent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationintent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Counting")
.setContentText("from" + rapida + "to" + lenta)
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
startForeground(new Random().nextInt(), notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
i need to make to run multiple of this at the same time no matter with what.
Its been a week since I've started working on an App to save All Instagram notifications so that if the sender unsend the message I can access the deleted message.
I figured out that I should use something called Notification Listener Service. I've read a lot of articles about it and I've also read the whole Android developer documentation about notifications but it's so complicated and I still don't know how to use this thing in my app.
I want to show all notifications in a list and generate text views dynamically and fill them with notifications.
Can someone please help me?
This is my MainActivity:
public class MainActivity extends Activity {
private TextView txtView;
private NotificationReceiver nReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView = (TextView) findViewById(R.id.textView);
nReceiver = new NotificationReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE");
registerReceiver(nReceiver,filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(nReceiver);
}
public void buttonClicked(View v){
if(v.getId() == R.id.btnCreateNotify){
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder ncomp = new NotificationCompat.Builder(this);
ncomp.setContentTitle("My Notification");
ncomp.setContentText("Notification Listener Service Example");
ncomp.setTicker("Notification Listener Service Example");
ncomp.setSmallIcon(R.drawable.ic_launcher);
ncomp.setAutoCancel(true);
nManager.notify((int)System.currentTimeMillis(),ncomp.build());
}
else if(v.getId() == R.id.btnClearNotify){
Intent i = new Intent("com.kpbird.nlsexample.NOTIFICATION_LISTENER_SERVICE_EXAMPLE");
i.putExtra("command","clearall");
sendBroadcast(i);
}
else if(v.getId() == R.id.btnListNotify){
Intent i = new Intent("com.kpbird.nlsexample.NOTIFICATION_LISTENER_SERVICE_EXAMPLE");
i.putExtra("command","list");
sendBroadcast(i);
}
}
class NotificationReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String temp = intent.getStringExtra("notification_event") + "\n" + txtView.getText();
txtView.setText(temp);
}
}
This also my NotificationsListener Class:
public class NLService extends NotificationListenerService {
private String TAG = this.getClass().getSimpleName();
private NLServiceReceiver nlservicereciver;
#Override
public void onCreate() {
super.onCreate();
nlservicereciver = new NLServiceReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.kpbird.nlsexample.NOTIFICATION_LISTENER_SERVICE_EXAMPLE");
registerReceiver(nlservicereciver,filter);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(nlservicereciver);
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i(TAG,"********** onNotificationPosted");
Log.i(TAG,"ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());
Intent i = new Intent("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE");
i.putExtra("notification_event","onNotificationPosted :" + sbn.getPackageName() + "\n");
sendBroadcast(i);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i(TAG,"********** onNOtificationRemoved");
Log.i(TAG,"ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText +"\t" + sbn.getPackageName());
Intent i = new Intent("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE");
i.putExtra("notification_event","onNotificationRemoved :" + sbn.getPackageName() + "\n");
sendBroadcast(i);
}
class NLServiceReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getStringExtra("command").equals("clearall")){
NLService.this.cancelAllNotifications();
}
else if(intent.getStringExtra("command").equals("list")){
Intent i1 = new Intent("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE");
i1.putExtra("notification_event","=====================");
sendBroadcast(i1);
int i=1;
for (StatusBarNotification sbn : NLService.this.getActiveNotifications()) {
Intent i2 = new Intent("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE");
i2.putExtra("notification_event",i +" " + sbn.getPackageName() + "\n");
sendBroadcast(i2);
i++;
}
Intent i3 = new Intent("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE");
i3.putExtra("notification_event","===== Notification List ====");
sendBroadcast(i3);
}
}
}
}
In my Application I have a Broadcast receiver (registered in manifest) class from which I want to send an Intent to MainActivity. Therefore I have another broadcast receiver (dynamically registered) in MainActivity and an Intent Filter. But I don't receive the Intent in Main Activity.
This is the code:
public class SmsReceiver extends BroadcastReceiver {
public static final String SMS_BUNDLE = "pdus";
public SmsReceiver(){
}
String TAG = SmsReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent){
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] sms = (Object[]) bundle.get(SMS_BUNDLE);
String str = "";
for (int i=0; i < sms.length; i++) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsbody = smsMessage.getMessageBody().toString();
str += smsbody;
}
Intent bcIntent = new Intent();
bcIntent.setAction("SMS_RECEIVED_ACTION");
bcIntent.addCategory(Intent.CATEGORY_DEFAULT);
bcIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
bcIntent.putExtra("message", str);
context.sendBroadcast(bcIntent);
}
}
}
and in the MainActivity:
public class MainActivity extends AppCompatActivity
{
public boolean receivedSMS;
public String displaySMS;
private BroadcastReceiver iReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String qqq = intent.getExtras().getString("message");
info2(intent.getExtras().getString("message"));
evalMsg(qqq);
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
graphInit();
timerInit();
smnInit();
}
#Override
protected void onResume(){
super.onResume();
IntentFilter iFilter = new IntentFilter();
iFilter.addAction("SMS_RECEIVED_ACTION");
registerReceiver(iReceiver, iFilter);
}
#Override
protected void onPause(){
unregisterReceiver(iReceiver);
super.onPause();
}
Does anyone know why the broadcast receiver in the main activity doesnt receive the intent? There should be a text displayed in the TextView but it is never shown. thanks for any idea
When receiving the intent via SmsReceiver you can't know if the Activity is up and in what state.
What you should consider is using startActivity(android.content.Intent) from within your SmsReceiver.onReceive(). This way you'll have the same intent object available within Activity.onCreate (just call the getIntent() method)
But if you want to stick to your original design of double broadcasts, then here is your answer.
I am running into an issue with the implementation of the Dale Lane MQTT solution.
I cannot seem to figure out how to retrieve the published message from the MQTT Client I am using.
I am not sure if I am utilizing the the onReceive() method incorrectly, but for now all I would like to do is log the broadcasted messages.
http://dalelane.co.uk/blog/?p=1599
The service I have implemented is exactly as listed here, I have no errors.
public class MQTTNotifier extends Activity implements OnClickListener {
String preferenceBrokerHost, preferenceBrokerTopic;
private StatusUpdateReceiver statusUpdateIntentReceiver;
private MQTTMessageReceiver messageIntentReceiver;
private EditText etBroker, etTopic;
Button btnSubscribe, btnStopService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mqttnotifier);
initValues();
// startService();
}
private void initValues() {
btnSubscribe = (Button) findViewById(R.id.btnSubscribe);
btnSubscribe.setOnClickListener(this);
btnStopService = (Button) findViewById(R.id.btnStopService);
btnStopService.setOnClickListener(this);
// if statement to see if sharedpreferences exist, if so reopen recievers
/*
* statusUpdateIntentReceiver = new StatusUpdateReceiver(); IntentFilter intentSFilter = new
* IntentFilter(MQTTService.MQTT_STATUS_INTENT); registerReceiver(statusUpdateIntentReceiver,
* intentSFilter);
*
* messageIntentReceiver = new MQTTMessageReceiver(); IntentFilter intentCFilter = new
* IntentFilter(MQTTService.MQTT_MSG_RECEIVED_INTENT); registerReceiver(messageIntentReceiver,
* intentCFilter);
*/
}
public class StatusUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle notificationData = intent.getExtras();
String newStatus = notificationData.getString(MQTTService.MQTT_STATUS_MSG);
}
}
public class MQTTMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle notificationData = intent.getExtras();
String newTopic = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_TOPIC);
String newData = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_MSG);
Log.e("NEW TOPIC", newTopic);
Log.e("NEW DATA", newData);
}
}
#Override
protected void onDestroy() {
unregisterReceiver(statusUpdateIntentReceiver);
unregisterReceiver(messageIntentReceiver);
}
private void startService() {
Intent svc = new Intent(this, MQTTService.class);
startService(svc);
}
private void stopService() {
Intent svc = new Intent(this, MQTTService.class);
stopService(svc);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(MQTTService.MQTT_NOTIFICATION_UPDATE);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnSubscribe:
etBroker = (EditText) findViewById(R.id.etBroker);
etTopic = (EditText) findViewById(R.id.etTopic);
preferenceBrokerHost = etBroker.getText().toString().trim();
preferenceBrokerTopic = etBroker.getText().toString().trim();
createSharedPreferences(preferenceBrokerHost, preferenceBrokerTopic);
establishRecievers();
startService();
break;
case R.id.btnStopService:
stopService();
}
}
private void createSharedPreferences(String broker, String topic) {
SharedPreferences settings = getSharedPreferences(MQTTService.APP_ID, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("broker", broker);
editor.putString("topic", topic);
editor.commit();
}
private void establishRecievers() {
statusUpdateIntentReceiver = new StatusUpdateReceiver();
IntentFilter intentSFilter = new IntentFilter(MQTTService.MQTT_STATUS_INTENT);
registerReceiver(statusUpdateIntentReceiver, intentSFilter);
messageIntentReceiver = new MQTTMessageReceiver();
IntentFilter intentCFilter = new IntentFilter(MQTTService.MQTT_MSG_RECEIVED_INTENT);
registerReceiver(messageIntentReceiver, intentCFilter);
}
}
It turns out that the issue was in regards to a simple mistake that was in regards to this line.
preferenceBrokerTopic = etBroker.getText().toString().trim();
I corrected the issue and now it corrects properly because it was not subscribing to the correct topic.
preferenceBrokerTopic = etTopic.getText().toString().trim();
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();
}