Display only whatsapp notifications in application - android

I have an application that runs a service listens to notifications but it is showing all notification, I want to show only whatsapp notifications so I check if my package equals to com.whatsapp but then it's not showing nothing, code:
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
if (pack == "com.whatsapp") {
TableRow tr = new TableRow(getApplicationContext());
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(getApplicationContext());
textview.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1.0f));
textview.setTextSize(20);
textview.setTextColor(Color.parseColor("#0B0719"));
textview.setText(Html.fromHtml(pack + "<br><b>" + title + " : </b>" + text));
tr.addView(textview);
tab.addView(tr);
}
}
};
}
am I checking if it equals wrong?
If needed, service code:
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker = sbn.getNotification().tickerText.toString();
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
NOTE : when I remove the if statement,everything is working fine and it shows com.whatsapp as the package. thank you guys

You have to use the equals() method to compare Strings. == only compares their references, not their values.
if ("com.whatsapp".equals(pack)) {
// ...
}

check for package name before sending your broadcast.
if ("com.whatsapp".equals(pack)) {
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}

Related

Android: Listen for notification update

Is there a way to listen if a notification is updated. For example if I receive a message in Messenger my notification listener will notice that, but once I receive a second message - the notification listener ignores that.
I have tried with cancelling notifications, but that did not work
My notification listener:
public class Reader extends NotificationListenerService{
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
int id = sbn.getId();
String ticker = sbn.getNotification().tickerText.toString();
Bundle extras = sbn.getNotification().extras;
final String title = extras.getString("android.title");
String tag = sbn.getTag();
int ides = extras.getInt("android.id");
final String ss = extras.getString("android.text").toString();
final String text = ss.toLowerCase();
if (pack.equals("com.facebook.orca")) {
String e = "Tah";
Log.e(e, pack);
Log.e(e, ticker);
Log.e(e, title);
Log.e(e, ss);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", ">" + text + "");
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
}

Transfering data from an activity to another and recomposing the name of varibles

I have menu Menu 1 containing 20 buttons bt1, bt2,..btn when you click a button should go to the main activity Main1 where a title and a text should be displayed. Main1 is extended to Text1 where the titles and texts are.
What's needed is that when you click on button2 for example the Main1 should display Title2 and Text2 and so on.
I did this in the Menu 1:
#Override
public void onClick(View v) {
//do common code here
Bundle bundle1 = new Bundle();
bundle1.putString("somekey1", act1);
Intent i = new Intent(getApplicationContext(), Main1.class);
i.putExtras(bundle1);
startActivity(i);
str= v.getResources().getResourceName(v.getId());
act1= Integer.toString(Integer.parseInt(str.substring(str.indexOf("bt")+2 )));
in the Main1 I did this:
num = Integer.parseInt(getIntent().getExtras().getString("somekey1"));
stringId1 = getResources().getIdentifier("title"+num, "string", getPackageName());
stringId2 = getResources().getIdentifier("text"+num, "string", getPackageName());
if (stringId1 > 0) {
title=getString(stringId1);
text2=getString(stringId2);
}
in the Text1 I did this:
public class Text extends Activity {
public String
title1="some title",
text1="some text",
title2="some title",
text2="some text",
titl3="333",
tex3="kar3",
title4="xxxxx",
text4="xxxxx",
title5="",
text5="",
But all of that doesn't work, and about to shake my head on the wall, as the bundle doesn't transfer the data, and stringId1 = getResources().getIdentifier("title"+num, "string", getPackageName());
also returns 0.
Help please`
Pass the intent as shown below:
Intent intent = new Intent(getApplicationContext(),Main1.class);
intent.putExtra("Key1", "Value1");
intent.putExtra("Key2", "Value2");
startActivity(intent);
And in the oncreate() of your Main1.class :
Intent dataIntent = getIntent();
String value1 = dataIntent.getStringExtra("Key1");
String value2 = dataIntent.getStringExtra("Key2");
Please try the following
#Override
public void onClick(View v) {
//do common code here
Bundle bundle1 = new Bundle();
str= v.getResources().getResourceName(v.getId());
act1= Integer.toString(Integer.parseInt(str.substring(str.indexOf("bt")+2 )));
bundle1.putString("somekey1", act1);
Intent i = new Intent(getApplicationContext(), Main1.class);
i.putExtras(bundle1);
startActivity(i);

Android: I need to delay a Notification

I've create a broadcast receiver that listen to the android.provider.Telephony.SMS_RECEIVED event and creates its own notification.
I also use the same receiver in the app to update the activities when an sms is received using a callback.
The problem is that the sms app notification event is dispatched after my notification, so when I update the sms is not preset in content://sms
I would like to delay my notification if it's possible, can't find how to do it.
here's the code:
public class SmsReceiver extends BroadcastReceiver {
Context context;
int nmessages = 0;
#Override
public void onReceive(Context context, Intent intent) {
//—get the SMS message passed in—
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String messages = "";
this.context = context;
if (bundle != null)
{
//—retrieve the SMS message received—
Object[] smsExtra = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[smsExtra.length];
nmessages = SmsHolder.getNumberUnreadSms(context) +1;
for (int i=0; i<msgs.length; i++)
{
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
//take out content from sms
String body = sms.getMessageBody().toString();
String address = sms.getOriginatingAddress();
messages += "SMS from " + address + " :\n";
messages += body + "\n";
putSmsToDatabase(sms, context );
}
//—display the new SMS message—
createNotification(SmsMessage.createFromPdu((byte[])smsExtra[0]), context);
updateActivity();
}
}
public void updateActivity(){
}
private void putSmsToDatabase( SmsMessage sms, Context context )
{
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
// Create SMS row
ContentValues values = new ContentValues();
values.put("address", sms.getOriginatingAddress().toString() );
values.put("date", mydate);
values.put("body", sms.getMessageBody().toString());
// values.put( READ, MESSAGE_IS_NOT_READ );
// values.put( STATUS, sms.getStatus() );
// values.put( TYPE, MESSAGE_TYPE_INBOX );
// values.put( SEEN, MESSAGE_IS_NOT_SEEN );
}
private void createNotification(SmsMessage sms, Context context){
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
String contentTitle;
if (nmessages < 2){
contentTitle = "SMS: " + ContactsInterface.getContactDisplayNameByNumber(sms.getOriginatingAddress(), context);
}else {
contentTitle = nmessages + " " + context.getResources().getString(R.string.new_messages);
}
// construct the Notification object.
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(contentTitle)
.setContentText(sms.getMessageBody())
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(getIconBitmap())
.setNumber(nmessages);
builder.setAutoCancel(true);
//(R.drawable.stat_sample, tickerText,
// System.currentTimeMillis());
// Set the info for the views that show in the notification panel.
//notif.setLatestEventInfo(this, from, message, contentIntent);
/*
// On tablets, the ticker shows the sender, the first line of the message,
// the photo of the person and the app icon. For our sample, we just show
// the same icon twice. If there is no sender, just pass an array of 1 Bitmap.
notif.tickerTitle = from;
notif.tickerSubtitle = message;
notif.tickerIcons = new Bitmap[2];
notif.tickerIcons[0] = getIconBitmap();;
notif.tickerIcons[1] = getIconBitmap();;
*/
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, Login.class);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
context,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
// Ritardo in millisecondi
builder.setContentIntent(resultPendingIntent);
// Note that we use R.layout.incoming_message_panel as the ID for
// the notification. It could be any integer you want, but we use
// the convention of using a resource id for a string related to
// the notification. It will always be a unique number within your
// application.
nm.notify(R.drawable.ic_drawer, builder.build());
}
private Bitmap getIconBitmap() {
BitmapFactory f = new BitmapFactory();
return f.decodeResource(context.getResources(), R.drawable.ic_sms);
}
}
If you just need to do it for a specific amount of time, probably the easiest way is to use a handler and use a postDelayed(). Something like this:
// SLEEP 5 SECONDS HERE ...
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// createNotification(SmsMessage.createFromPdu((byte[])smsExtra[0]), context);
updateActivity();
}
}, 5000);
If you want to wait for another action, that's a bit more complicated.

How do i send multiple Integers to a new activity?

I have a way that I know is not the best way of sending them over rite now but I'm sending them as strings and converting them to an Int on the reciver side, the problem is when I do the conversion it crashes on my phone. This is what I have on my sender side:
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, PayTracker.class);
// hourly wage send
EditText editText = (EditText) findViewById(R.id.hourly_wage);
String message1 = editText.getText().toString();
intent.putExtra(MESSAGE_1, message1);
// ot wage send
EditText editText1 = (EditText) findViewById(R.id.ot_wage);
String message2 = editText1.getText().toString();
intent.putExtra(MESSAGE_2, message2);
// hours per day send
EditText editText2 = (EditText) findViewById(R.id.hours_day);
String message3 = editText2.getText().toString();
intent.putExtra(MESSAGE_3, message3);
// start new activity
startActivity(intent);
And this is what is on my reciving side:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_tracker);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Receive messages from options page
Intent intent = getIntent();
String message1 = intent.getStringExtra(Options.MESSAGE_1);
String message2 = intent.getStringExtra(Options.MESSAGE_2);
String message3 = intent.getStringExtra(Options.MESSAGE_3);
// convert string to integer
int HW = Integer.valueOf(message1);
int OTW = Integer.valueOf(message2);
int HPD = Integer.valueOf(message3);
Ive tested everything and its the conversion that is causing the app to crash, i was hoping somebody could help me make it not crash or give me a whole new way sending an int to my second activity insted of sending a string and converting it.
Thank you!
=======================================================================
Here is my new code with all your help!
Sending:
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, PayTracker.class);
// Gather text from text boxes
EditText editText = (EditText) findViewById(R.id.hourly_wage);
EditText editText1 = (EditText) findViewById(R.id.ot_wage);
EditText editText2 = (EditText) findViewById(R.id.hours_day);
//Create String from text
String message1 = editText.getText().toString();
String message2 = editText1.getText().toString();
String message3 = editText2.getText().toString();
//Convert String to Int
int HW = 0, OTW = 0, HPD = 0;
try{
HW = Integer.valueOf(message1);
OTW = Integer.valueOf(message2);
HPD = Integer.valueOf(message3);
}
catch(NumberFormatException nfe){
//do something else here
//for e.g. initializing default values to your int variables
}
// Send Integers to PayTracker.java
intent.putExtra(MESSAGE_HW, HW);
intent.putExtra(MESSAGE_OTW, OTW);
intent.putExtra(MESSAGE_HPD, HPD);
// start new activity
startActivity(intent);
}
Receiving side:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_tracker);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Receive messages from options page
Intent intent = getIntent();
int HW = intent.getIntExtra(Options.MESSAGE_HW, 0);
int OTW = intent.getIntExtra(Options.MESSAGE_OTW, 0);
int HPD = intent.getIntExtra(Options.MESSAGE_HPD, 0);
// set textview
TextView textView = (TextView) this.findViewById(R.id.yourpay);
textView.setText(String.valueOf(HW));
}
You don't need to pass Integers as Strings to be converted back in the receiving Activity. Intents can hold Integers as well as Strings.
Simply add your data like you normally would:
int foo = 5;
Intent intent = new Intent(this, bar.class);
intent.putExtra("foobar", foo);
And then retrieve your int from the intent in the receiving Activity as follows.
Intent intent = getIntent();
int foo = intent.getIntExtra("foobar", 0);
Intents can hold more data than just Strings. In fact, take a look at the documentation. You can see that Intents can hold Longs, Doubles, Floats, Parcelables, etc.
Pass data from one activity to another activity "String" value.useing intent
Activityone
Intent intent = new Intent(Activityone.this,Activitytwo.class)
intent.putExtra("TYPE", type);
startActivity(intent);
Activitytwo
Intent intent =getIntent();
Receivevalue =intent.getExtras().getString("TYPE");
(OR)
Receivevalue = getIntent().getExtras().getString("TYPE");
Pass data from one activity to another activity "Integer" value.useing intent
Activityone
Intent intent = new Intent(Activityone.this,Activitytwo.class)
intent.putExtra("TYPE", type);
startActivity(intent);
Activitytwo
Intent intent = getIntent();
value = intent.getIntExtra("TYPE", 0);
// Type = intent.getIntExtra(name, defaultValue);
Try something like this on the send side:
String message1 = editText.getText().toString();
intent.putExtra("MESSAGE_1", message1);
String message2 = editText1.getText().toString();
intent.putExtra("MESSAGE_2", message2);
String message3 = editText2.getText().toString();
intent.putExtra("MESSAGE_3", message3);
Receive side:
if (getIntent() != null) {
if (getIntent().getExtras() != null) {
String mess1 = getIntent().getExtras().getString("MESSAGE_1");
String mess2 = getIntent().getExtras().getString("MESSAGE_2");
String mess3 = getIntent().getExtras().getString("MESSAGE_3");
}
}
You can achieve your goal using following code
In Your Calling Activity
Intent value = new Intent(YourCallingActivity.this,DestinationActivity.class);
value.putExtra("integerone", integeronevalue);
value.putExtra("integertwo", integertwovalue);
value.putExtra("integerthree", integertwovalue);
startActivity(value);
In Destination Activity
int integerone = getIntent().getExtras().getInt("integerone");
int integertwo = getIntent().getExtras().getInt("integertwo");
int integerthree = getIntent().getExtras().getInt("integerthree");
Hope it helps
Encapsulate the conversion part within try/catch block, because your strings may not be convertible into integer values.
int HW, OTW, HPD;
try{
HW = Integer.valueOf(message1);
OTW = Integer.valueOf(message2);
HPD = Integer.valueOf(message3);
}
catch(NumberFormatException nfe){
//do something else here
//for e.g. initializing default values to your int variables
}
*Or more appropriately, pass the integer values in your sending part and receive them as it is.

Passing data between activities - Android SDK

I have read the previously posted questions and answers for 2 days and I've tried every variation suggested as well as setting my launchMode attribute to "standard" in my manifest.
I'm trying to pass data from my second activity back to my first activity after pressing a button. After I press the button, the first activity is launched but it doesn't go back to my onActivityResult() method. I can't figure out why this is happening.
Here's my code from activity 2:
Button btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Check that message is printed out to LogCat
System.out.println("hello test1 Activity2");
EditText band = (EditText) findViewById(R.id.txtBand);
band.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(9)
});
EditText album = (EditText) findViewById(R.id.txtAlbum);
album.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(9)
});
final Spinner genre = (Spinner) findViewById(R.id.spin_genre);
TextView selection = (TextView)genre.getSelectedView();
CharSequence strBand = band.getText();
CharSequence strAlbum = album.getText();
CharSequence strGenre = selection.getText();
//Check that we got input values
System.out.println("hello test Activity2- " +
strBand + " - " + strAlbum + " - " + strGenre);
//**********Intent Declaration************
Intent i = new Intent(getApplicationContext(), Activity1.class);
i.putExtra("strBand", strBand);
i.putExtra("strAlbum", strAlbum);
i.putExtra("strGenre", strGenre);
startActivityForResult(i, 0);
setResult(RESULT_OK, i);
finish();
}
});
Here's activity 1:
public class Activity1 extends Activity {
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button addAlbum = (Button) findViewById(R.id.btnMain);
addAlbum.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent();
i.setClassName("jorge.jorge.jorge",
"jorge.jorge.jorge.Activity2");
startActivity(i);
}
});
}// end of onCreate()
//******************Callback Method****************************
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//Checks if we got to ActivityResult
System.out.println("hello test 2: We got to Activity1");
if (resultCode == RESULT_OK)
{
Bundle returndata = data.getExtras();
String strAlbum = returndata.getString("strAlbum");
String strBand = returndata.getString("strBand");
String strGenre = returndata.getString("strGenre");
// check to see if we got the variable values from activity2
System.out.println("hello test 2: We got to Activity1 with variables - "
+ strBand + " - " + strAlbum + " - " + strGenre);
//Create table layout to contains views with variable values
TableLayout table = new TableLayout(this);
table.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
//creates row with parameters
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
//text views to contain variable values
TextView tv1 = new TextView(this);
tv1.setText(strBand);
row.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setText(strAlbum);
row.addView(tv2);
TextView tv3 = new TextView(this);
tv3.setText(strGenre);
row.addView(tv3);
//adds the table row to the table layout
table.addView(row);
}
}// end onActivityResult()
}
I'm not sure if my activity callbacks are not placed properly in the code or if I'm not firing the intent properly or if I'm not setting up the callback with the right method or what. I know this topics has been discussed but I'm out of ideas. Thanks.
You've just got it backwards. If Activity1 is supposed to startActivity2 and Activity2 is supposed to send the result back to Activity1, you need to do it like this:
in Activity1:
Intent i = new Intent();
i.setClassName("jorge.jorge.jorge", "jorge.jorge.jorge.Activity2");
startActivityForResult(i); // This starts Activity2 and waits for the result
in Activity2:
Intent i = new Intent(getApplicationContext(), Activity1.class);
i.putExtra("strBand", strBand);
i.putExtra("strAlbum", strAlbum);
i.putExtra("strGenre", strGenre);
setResult(RESULT_OK, i);
finish(); // This closes Activity2 and generates the callback to Activity.onActivityResult()

Categories

Resources