If message contains a text then use the answer (Android Studio) - java

If the message received have text "1" then show in-app message "Da" (already done part with show app)
If the message received doesn't have text "1" then don't show the app.
MainActivity:
public class MainActivity extends AppCompatActivity {
/* Button msg; */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* In beta mode
PreferenceManager.setDefaultValues(this, R.xml.preferences, true); */
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String address = extras.getString("MessageNumber");
String message = extras.getString("Message");
TextView addressField = (TextView) findViewById(R.id.address);
TextView messageField = (TextView) findViewById(R.id.message);
addressField.setText("ALERT From : " + address);
messageField.setText("ALERT Type : " + message);
}
/* msg = (Button)findViewById(R.id.btn_msg);
msg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});*/
SimpleSMSReciver class
public class SimpleSmsReciever extends BroadcastReceiver {
private static final String TAG = "Message recieved";
#Override
public void onReceive(Context context, Intent intent) {
Bundle pudsBundle = intent.getExtras();
Object[] pdus = (Object[]) pudsBundle.get("pdus");
SmsMessage messages =SmsMessage.createFromPdu((byte[]) pdus[0]);
// Start Application's MainActivty activity
Intent smsIntent=new Intent(context,MainActivity.class);
smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsIntent.putExtra("MessageNumber", messages.getOriginatingAddress());
smsIntent.putExtra("Message", messages.getMessageBody());
context.startActivity(smsIntent);
// Get the Sender Message : messages.getMessageBody()
// Get the SenderNumber : messages.getOriginatingAddress()
Toast.makeText(context, "Message Received From :"+messages.getOriginatingAddress()+"\n"+ messages.getMessageBody(), Toast.LENGTH_LONG).show();
}

If the message received doesn't have text "1" then don't show the app.
if(!extras.getString("Message").equals("1"))finish();

Related

How to send command linux from one device to another conneted via usb otg?

I made application which should send linux command to another device, when are together connected via ust otg.
How can i send my command to another device?
I made communication, and i can read for example model device, now i would like send command to see ip address connected device
Ok, sorry my fault
Here I is my MainActivity
private static final String TAG = "UsbEnumerator";
private TextView mStatusView, mResultView, showCommand;
private Button buttonRefresh, sendCommand;
private UsbManager usbManager;
private EditText writeCommand;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mStatusView = (TextView) findViewById(R.id.mStatusView);
mResultView = (TextView) findViewById(R.id.mResultView);
showCommand = (TextView) findViewById(R.id.showCommand);
buttonRefresh = (Button) findViewById(R.id.buttonRefresh);
sendCommand = (Button) findViewById(R.id.sendCommand);
writeCommand = (EditText) findViewById(R.id.writeCommand);
mResultView.setMovementMethod(new ScrollingMovementMethod());
buttonRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
finish();
overridePendingTransition(0,0);
startActivity(i);
overridePendingTransition(0,0);
}
});
sendCommand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View t) {
SendCommandExecutor exe = new SendCommandExecutor();
String command = writeCommand.getText().toString();
String outp = exe.Executer(command);
showCommand.setText(outp);
Log.d("Output", outp);
}
});
usbManager = getSystemService(UsbManager.class);
IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUsbReceiver, filter);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mUsbReceiver);
}
BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
printStatus("Delete");
printDeviceDescription(device);
}
}
}
};
private void handleIntent(Intent intent) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
printStatus("Adding");
printDeviceDetails(device);
} else {
printStatus("Remove");
printDeviceList();
}
}
I would like send linux command (for example check ip address) when i have connected device via ust otg. Should i execute command in here?
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
printStatus("Delete");
printDeviceDescription(device);
}
}
}
};

Keep recent SMS received in TextView

I'm trying to keep the recent received SMS to TextView, but when i close the app then open it again the TextView returns to empty is there a way to keep the recent received SMS in TextView even if its closes the app
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
TextView addressField = (TextView) findViewById(R.id.tvAddress);
TextView messageField = (TextView) findViewById(R.id.tvMessage);
if(extras != null){
String address = extras.getString("MessageNumber");
String message = extras.getString("Message");
addressField.setText(address);
messageField.setText(message);
}
}
SimpleSmsReceiver.java
private static final String TAG = "Message recieved";
#Override
public void onReceive(Context context, Intent intent) {
Bundle pudsBundle = intent.getExtras();
Object[] pdus = (Object[]) pudsBundle.get("pdus");
SmsMessage messages = SmsMessage.createFromPdu((byte[]) pdus[0]);
Intent smsIntent=new Intent(context,MainActivity.class);
smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String sender = messages.getDisplayOriginatingAddress();
smsIntent.putExtra("MessageNumber", sender);
smsIntent.putExtra("Message", messages.getMessageBody());
if(PhoneNumberUtils.compare("12345", sender) | PhoneNumberUtils.compare("123456", sender) ) {
context.startActivity(smsIntent);
Toast.makeText(context, "SMS Received From Device" , Toast.LENGTH_LONG).show();
}
}
Use Shared Preferences in your SimpleSmsReceiver class since you're only passing data to the MainActivity using Intent but this won't save the data for the next time user opens the app.
In your SimpleSmsReceiver (e.g):
SharedPreferences.Editor editor = getSharedPreferences("YourKey", MODE_PRIVATE).edit();
editor.putString("MessageNumber", sender);
editor.putString("Message", messages.getMessageBody())
editor.apply();
Then to retrieve those values inside your MainActivity:
SharedPreferences prefs = getSharedPreferences("YourKey", MODE_PRIVATE);
String messageNumber = prefs.getString("MessageNumber", null);
String message = prefs.getString("Message", null);

How to pass data from Receiver to Activity using interface?

I'm trying to pass the data from the brodcast receiver to the activity to display it on the view using an interface, but, it's not working.Here are my files,MainActivity.java
public class MainActivity extends AppCompatActivity implements OtpPassing {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onReceive(String msg) {
Toast.makeText(this, "o" + msg, Toast.LENGTH_SHORT).show();
textView = (TextView) findViewById(R.id.textView);
textView.setText("OTP: " + msg);
}
}
OtpPassing.java
public interface OtpPassing {
public void onReceive(String msg);
}
Receiver.java
public class Receiver extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the 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();
Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);
String otp = getOtp(message);
Toast.makeText(context, otp, Toast.LENGTH_LONG).show(); //This is working fine
OtpPassing otpPassing = new MainActivity();
otpPassing.onReceive(otp); //This is not working
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
private String getOtp(String message) {
String otp = null;
int index = message.indexOf("otp:");
if(index != -1){
int start = index + 5;
otp = message.substring(start, start+4);
}
return otp;
}
}
The receiver is woking(it's displaying the message on a Toast) but why is displaying the message on the screen via MainActivity not working?
You can create a broadcast receiver as a data member of your activity. You register for it in onCreate and unregister in onDestroy (or onStart and onStop).
That way the receiver has a reference to the parent activity and you can do whatever.
public class MainActivity extends AppCompatActivity implements OtpPassing {
private TextView textView;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//Access the parent activity as follows
MainActivity.this.textView.setText("...");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//instantiate and register the receiver
setContentView(R.layout.activity_main);
}
#Override
protected void onDestroy() {
// Unregister the receiver here
super.onDestroy();
}
Here better way (I suppose) would be to use Android Intents
in your receiver, something like this
Intent intent = new Intent(context,MainActivity.class);
intent.putExtra(.....);
startactivity(intent);
now in your MainActivity, override onNewIntent(). Here check for the 'extras' you had passed from the receiver.
Please note, this might result in having multiple MainActivities running in your phone if your "older" MainActivity was not killed by the time this intent was passed via receiver. To overcome this, use 'singleTop' or similar flags in your Manifest file

Notification will not open Activity

I have an application where the user may send recipes to others with the application.
Right now, the app is able to send the notification, however, when the notification is clicked, it does not open the intended activity (SmsViewActivity) it simply closes the drawer.
Here is the code for the SmsViewActivity:
public class SmsViewActivity extends Activity {
private static final String TAG = "SmsViewActivity";
private static final String SMS_FOOD = "food_recieved";
private FoodJSONSerializer mSerializer;
public Button mSaveButton, mDismissButton;
public int mNotificationId;
public String message;
private EditText mTitleField;
private CheckBox mImperialCheckBox;
private CheckBox mMetricCheckBox;
private EditText mServingsField;
private EditText mDirectionsField;
private Spinner mMetricSpinner;
private Spinner mImperialSpinner;
Food mFood;
private String msg;
private Activity mActivity;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mActivity = this;
setContentView(R.layout.sms_view);
mSaveButton = (Button) findViewById(R.id.save_button_sms);
mDismissButton = (Button) findViewById(R.id.dismiss_button_sms);
this.msg = getIntent().getStringExtra("message");
try {
JSONObject jsonRecipe = new JSONObject(this.msg);
this.mFood = new Food(jsonRecipe);
Log.i(TAG, "Food = " + mFood);
} catch (JSONException e) {
e.printStackTrace();
}
mNotificationId = getIntent().getIntExtra("notificationid", 0);
if (mNotificationId == 0) {
Log.e(TAG, "Could not retrieve notification ID.");
Toast.makeText(this, "A fatal error has occurred in SMS viewer.",
Toast.LENGTH_LONG).show();
finish();
}
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationMgr = (NotificationManager) getSystemService(ns);
notificationMgr.cancel(mNotificationId);
this.mTitleField = (EditText) findViewById(R.id.food_title_sms);
this.mTitleField.setText(mFood.getTitle());
this.mServingsField = (EditText) findViewById(R.id.food_servings_sms);
this.mServingsField.setText(Integer.toString(mFood.getServings()));
this.mDirectionsField = (EditText) findViewById(R.id.directions_text_sms);
this.mDirectionsField.setText(mFood.getDirections());
this.mSaveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FoodStorage.get(mActivity).addFood(mFood);
finish();
}
});
this.mDismissButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
backToList();
finish();
}
});
}
public void backToList() {
Intent i = new Intent(this, FoodListFragment.class);
startActivity(i);
}
}
Also here is the receiver Activity:
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
Bundle bundle = intent.getExtras();
Map<String, String> msgTexts = new LinkedHashMap<String, String>();
if (bundle != null){
Object[] pdus = (Object[]) bundle.get("pdus");
for (Object pdu : pdus) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
String incomingMsg = message.getMessageBody();
String originatingNumber = message.getOriginatingAddress();
Log.i(TAG, "Rcvd: from " + originatingNumber + " Msg: " + incomingMsg);
msgTexts.put(originatingNumber, incomingMsg);
smsMessage = incomingMsg;
}
}
processMessages(msgTexts, mNextNotificationId);
}
public void processMessages( Map<String, String> msgTexts, int notificationId ){
for (Entry<String, String> entry : msgTexts.entrySet()) {
Log.i(TAG, "Processing message: " + entry.getValue());
Intent notificationIntent = new Intent(mContext, SmsViewActivity.class);
notificationIntent.putExtra("message", entry.getValue());
notificationIntent.putExtra("sender", entry.getKey());
notificationIntent.putExtra("notificationid", notificationId);
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Recipe Received")
.setContentTitle("Recipe Received")
.setContentIntent(resultPendingIntent)
.setContentText("from " + entry.getKey())
.setWhen(System.currentTimeMillis());
NotificationManager notificationMgr = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationMgr.notify(notificationId++, mBuilder.build());
}
}
Try changing the intent flag to:
PendingIntent.FLAG_CANCEL_CURRENT
Otherwise it just updates the existing intent. It should be possible to have an onNewIntent handler in your activity, but I found this works more reliably.

How to receive multiple values using an intent

I have my main activity using the startActivityForResult method which calls an activity that i need to return two string values from. I have it working to return one, but even with all the tutorials and other questions on here i have read i cant seem to get it to return the two values. Below is my code.
here is where i start the second activity:
Button button = (Button) findViewById(R.id.add);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(addM, 1);
}
});
Here is the activity it starts, i need to return the text that is in the titleField(which works now) and the yearField
public class AddMovie extends Activity {
String movieTitle, movieYear;
EditText titleField, yearField;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
titleField = (EditText) findViewById(R.id.titleField);
yearField = (EditText) findViewById(R.id.yearField);
save = (Button) findViewById(R.id.saveMovie);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.setData(Uri.parse(titleField.getText().toString()));
setResult(RESULT_OK, data);
//data.setData(Uri.parse(yearField.getText().toString()));
//setResult(RESULT_OK, data);
finish();
}
});
}
}
Here is the method in my main class that receives results
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == request_Code)
{
if(resultCode == RESULT_OK)
{
tempTitle = data.getData().toString();
//tempYear = data.getStringExtra("movieYear");
Toast.makeText(this, tempTitle, Toast.LENGTH_SHORT).show();
dbAddMovie(tempTitle, tempYear);
}
}
}
The code that is commented out was one attempt at making it receive multiple values, although they failed. Any help with this situation would be great. Thanks!
You should use something like:
Intent returnIntent = new Intent();
returnIntent.putExtra("title",titleField.getText().toString());
returnIntent.putExtra("year",yearField.getText().toString());
setResult(RESULT_OK,returnIntent);
finish();
And on your main activity, onActivityResult:
tempTitle = data.getStringExtra("title");
tempYear = data.getStringExtra("year");
use data.putExtra("keys", data); instead of data.setData(.....)
and get data like;
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
String value = extras.getString("keyName");
}
You should be able be put extras on your intent and get that data through an associated tag. This is how I'm doing it from an Activity's onCreate.
Intent mIntent = new Intent(this, MainActivity.class);
mIntent.putExtra("your_tag", "the string you want to get");
startActivity(mIntent);
finish();
Then in the activity you want that data (the MainActivity or whatever you're calling it)....
Intent intent = getIntent();
String value = intent.getExtras().getString("your_tag");
It may also be worth noting that you can Override the onNewIntent in your MainActivity to handle new Intents coming in, mine currently looks like...
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
Try this
public class AddMovie extends Activity {
String movieTitle, movieYear;
EditText titleField, yearField;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
titleField = (EditText) findViewById(R.id.titleField);
yearField = (EditText) findViewById(R.id.yearField);
save = (Button) findViewById(R.id.saveMovie);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra("title_field", titleField.getText().toString);
data.putExtra("year_field", yearField.getText().toString);
setResult(RESULT_OK, data);
finish();
}
});
}
And this
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == request_Code)
{
if(resultCode == RESULT_OK)
{
tempTitle = data.getStringExtra("title_field");
tempYear = data.getStringExtra("year_field");
Toast.makeText(this, tempTitle, Toast.LENGTH_SHORT).show();
dbAddMovie(tempTitle, tempYear);
}
}
}
You can use a putExtra method on your Intent:
data.putExtra("title", movieTitle);
data.putExtra("year", movieYear);
Then in the Activity that opens, you can get this data as follows:
String title, year;
Intent data = getIntent();
if (data != null) {
title = data.getExtras().getString("title");
year = data.getExtras().getString("year");
}
You can create a new intent and then add your two variables
Intent i = new Intent(getApplicationContext(), asd8.as.hwapp.timemonday.class);
i.putExtra("username",username);
i.putExtra("password", password);
startActivity(i);
And then retrieving the information in your new activity as so;
public void getInformation(){
Bundle extras = getIntent().getExtras();
if (extras != null) {
username = extras.getString("username");
password = extras.getString("password");
}
}

Categories