I found many similar answered issues here at SO but all of them seems to me slighty different from the mine.
I have my MainActivity Class that recall the addInfo() function defined in the same class. Consider also that addInfo function access the activity_ main Layout.:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
String[] saInfoTxt = {"App Started"};
addInfo("APP",saInfoTxt);
...
}
public void addInfo(String sType, String[] saInfoTxt) {
Date dNow = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String sNow = dateFormat.format(dNow);
LinearLayout layout = (LinearLayout) findViewById(R.id.info);
String sInfoTxt =TextUtils.join("\n", saInfoTxt);
sInfoTxt= sType + " " + sNow + "\n" + sInfoTxt;
TextView txtInfo = new TextView(this);
txtInfo.setText(sInfoTxt);
txtInfo.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
((LinearLayout) layout).addView(txtInfo);
};
}
Now I have a second class that respond to a Receiver to intercept incoming SMS. This class needs to recall the MainActivity.addInfo() function but I'm not able to do so:
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
// get sms objects
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus.length == 0) {
return;
}
// large message might be broken into many
SmsMessage[] messages = new SmsMessage[pdus.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
sb.append(messages[i].getMessageBody());
}
String sender = messages[0].getOriginatingAddress();
String message = sb.toString();
String[] saInfoTxt = {"Sender: " + sender,"Message: " + message};
MainActivity.addInfo("SMS", saInfoTxt);
}
}
}
}
If I define the addInfo() as static then the internal code is faulty. If I leave it as non-static the second class doesn't see the addInfo()
Could someone point me to the right direction?
Thanks in advance