I am relatively new to Android programming, but have had experience in Java and other coding languages. As part of a program that I am currently making, I want to be able to send a pre-defined email when a button is pressed. I am currently looking at this code:
Sending Email in Android using JavaMail API without using the default/built-in app
I am currently able to start an intent to start the MailSenderActivity.class. However, I am not able to understand how that is able to send an email through the GmailSender.class. I believe that I am misunderstanding how to use the code provided. Am I supposed to create two separate intents that will start both activities up, one after each other, in the code on the home page, as below? If not, how would I do it?
public void SendEmail(View v) {
Intent i = new Intent(getBaseContext(), MailSenderActivity.class);
Intent j = new Intent(getBaseContext(), GMailSender.class);
startActivity(i);
}
Also, I am wondering about the defined spaces for to/from, subject, body and the like in the code. I see that the MailSenderActivity.class has
try {
GMailSender sender = new GMailSender("username#gmail.com", "password");
sender.sendMail("This is Subject",
"This is Body",
"user#gmail.com",
"user#yahoo.com");
Are the user#gmail.com and user#yahoo.com both the recipients of the email? And are there any other places in the code where I am supposed to define the contents of the email?
Thanks for your time.
Scroll down and read the rest of the answer, you'll see that the sendMail() method gives all the clues:
public synchronized void sendMail(String subject, String body, String sender, String recipients)
So:
"user#gmail.com" is the sender (From field).
"user#yahoo.com" is the recipient (To field). You can specify more with commas, eg
"user#yahoo.com,user_2#gmail.com"
You would also see that GMailSender is just a class, not an Activity. Therefore, it does not need an Intent; just instantiate the class. Also, MailSenderActivity is a code sample demonstrating the implementation of GMailSender. You do not have to use it.
Eg
public void SendMail (View v) {
try {
GMailSender sender = new GMailSender("your_username#gmail.com", "password");
sender.sendMail("Subject",
"Email body",
"Fromfield#gmail.com",
"toField#example.com");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
Also keep in mind Java naming conventions state that methods should start with a lowercase letter. You should adhere to those conventions and refactor your code appropriately.
Related
I've managed to send SMS containing verification code from my app using SmsManager and SmsReceiver. But it's just like a normal SMS message. I wonder if I can tell to device that the SMS is containing code, thus user's device will automatically open popup dialog to ask user wether they will copy the code to clipboard or not.
I know several apps also do that. I was never capture the screenshot of the popup dialog I mean, but I hope you get the idea. (the popup is from android/system, not from apk)
Even the button is shown inside the SMS too:
How can we achieve this?
This is my current code in my activity:
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(val_no_hp, null, "Kode verifikasi aplikasi: " + kode_verifikasi, null, null);
kode_otp_rcv = new SmsReceiver(MainActivity.this);
IntentFilter kode_otp_filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(kode_otp_rcv, kode_otp_filter);
And this is my SmsReceiver class:
public class SmsReceiver extends BroadcastReceiver {
private MainActivity act;
private static int PANJANG_KODE_VERIFIKASI = 4;
public SmsReceiver(MainActivity act) {
this.act = act;
}
#Override
public void onReceive(Context context, Intent intent) {
SmsMessage[] msgs = Telephony.Sms.Intents.getMessagesFromIntent(intent);
SmsMessage msg = msgs[0];
String body = msg.getMessageBody();
String kode = body.substring(body.length() - PANJANG_KODE_VERIFIKASI);
// currently my app submit verification automatically when SMS arrived
// act.verifikasiOTP(kode, msg.getOriginatingAddress());
}
}
This is not possible, this functionality is not provided by android and is built by application developers themselves, the logic is private and varies from app to app, some apps may recognise some codes, whilst others may not.
I send my verification SMS like this:
code: 123456 Your code from Example.com
The important text is : code: 1111 at the begining
and in android mobiles, automatic copy is enabled .
I know its a long time from this question but I answer :)
I think it depends on the phone and OS but by the way the thing that I got is that if you write code like this :
:1234
PS: 1234 is a sample code
if the Mobile supports it, it will show the pop up copy code.
My app is using a NotificationListener to read out messages from various 3rd party apps, for example WhatsApp.
So far I was able to send a reply if only one chat is unread, the code is below.
However, in the case with WhatsApp, getNotification().actions returns a null object when more than two chats are unread, as the messages are bundled together. As you can see in the pictures below, if the notifications are extended there is an option to send a direct reply as well, therefore I am certain that it is possible to utilize this, also I think apps like PushBullet are using this method.
How could I access the RemoteInput of that notification?
public static ReplyIntentSender sendReply(StatusBarNotification statusBarNotification, String name) {
Notification.Action actions[] = statusBarNotification.getNotification().actions;
for (Notification.Action act : actions) {
if (act != null && act.getRemoteInputs() != null) {
if (act.title.toString().contains(name)) {
if (act.getRemoteInputs() != null)
return new ReplyIntentSender(act);
}
}
}
return null;
}
public static class ReplyIntentSender {
[...]
public final Notification.Action action;
public ReplyIntentSender(Notification.Action extractedAction) {
action = extractedAction;
[...]
}
private boolean sendNativeIntent(Context context, String message) {
for (android.app.RemoteInput rem : action.getRemoteInputs()) {
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putCharSequence(rem.getResultKey(), message);
android.app.RemoteInput.addResultsToIntent(action.getRemoteInputs(), intent, bundle);
try {
action.actionIntent.send(context, 0, intent);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
return false;
}
}
Some explanation how the above code works: Once a notification is received the app tries to get the actions and checks if the name is in the title of a remoteInput (normally it is in the format of "Reply to $NAME"), if that is found the Action is saved into a ReplyIntentSender class, which, when triggered by sendNativeIntent, cycles through all RemoteInputs of that Action and adds the message to the intent. If more than one chat is unread, getNotification().actions returns null.
Below are two screenshots, the first one where it is working without any problems and the second one where it doesn't.
You can consider this as my suggestion. I have done bit research on this and come up with following conclusions.(Also it looks like you have done plenty of research on this so it might be possible that you aware about what I wrote below)
Numerous apps send Wear specific notifications, and many of those contain actions accessible from an Android Wear device. We can grab those Wear notifications on the device, extracting the actions, finding the reply action (if one exists), populating it with our own response and then executing the PendingIntent which sends our response back the original app for it to send on to the recipient.
To do so you can refer this link (A nice workaround by Rob J). You can also refer this link in this context (Great research work done by Michał Tajchert).(You might need to work around with NotificationCompat.isGroupSummary)
This is what I feel(Might be I am totally wrong)
.actions method returns Array of all Notification.Action
structures attached to current notification by addAction(int,
CharSequence, PendingIntent), Here addAction method is deprecated
one so it might not working as intended.
I am not able to test this at my end otherwise I will love to provide a working solution with code.
Hope this will help you. Happy Coding!!!
I am thinking of using Skiller to manage my multiplayer game and had some questions. I was hoping to find some tutorials on how to use it, but I'll have to look through the code and the examples to figure it out. From what I understand, the data sent back and forth in a turn based game (payload) is going to be a string. This means all my information will need to be condensed into a string and then extracted out on the other end?
For example, Pikachu wants to use Thundershock on Pidgey.
Info to send: MoveName("Thundershock"), movePower("40"), specialAttack("55")
(I could put a key at the beginning to help me figure out what is being sent.)
String payload = "Move;Thundershock; 40; 55";
Then the other player's game would take that info and figure out the damage done and send that info back
payload = "Damage; Super Effective; 23"
How does this sound?
SKApplication.getInstance().getGameManager().getTurnBasedTools().makeMove(gameId, event, payload, chatline,
new SKListenerInterface<SKGameMoveResponse>(){
#Override
public void onResponse(SKGameMoveResponse response){
String gameId = response.getGameId();
eTBGameState state = response.getGameState();
String payload = response.getPayload();
String chatline = response.getChatline();
// handle opponent's move – explained in the next section
}
#Override
public void onError(SKStatusResponse response) {
// failed to send the move
}
});
Here is the documentation site
In my app if any number is set then on clicking it starts a call on that number, and if any website link is given then also it shows that underline and on clicking that it opens the browser.
Similarly, I want to open the email client if any email address is set in the textview and show it underline.
Here you will get about patterns.
Initially when the screen starts you need to check for the type of value and then set the styles and click functions for your TextView like below. I guess you know about how to send emails, make calls and open a web browser with a link. I have made three click listeners but using one is good. You can have a flags for that and depending on that you can make operations instead.
public void setStyleAndFunction(CharSequence target) {
if(Patterns.EMAIL_ADDRESS.matcher(target).matches()) {
textview.setonClickListener() {
// send email
}
}
if(Patterns.PHONE.matcher(target).matches()) {
textview.setonClickListener() {
// make call
}
}
if(Patterns.WEB_URL.matcher(target).matches()) {
//set style (underline)
textview.setonClickListener() {
//open a web browser
}
}
}
Try It works for me :
Just write this code TextView ClickEvent or set as Linkify and call this.
Intent i2 = new Intent(android.content.Intent.ACTION_SEND);
i2.setType("text/html");
i2.putExtra(Intent.EXTRA_CC,new String[]{"Your CC Mail ID"});
i2.putExtra(Intent.EXTRA_EMAIL , new String[]{"Your TO Mail ID"});
i2.putExtra(android.content.Intent.EXTRA_SUBJECT, "Your Mail Body");
I have some text in my application that says in case you need extra help, please email us and here is the email address, blah, blah.
But I want them to be able to click the email link and have their email client open. Is that possible? Or is that bad practice?
If it is reasonable practice, how can it be done?
This is a very reasonable request and the Linkify class will turn every email address into an appropriate link for you. Simply add the autoLink attribute to your XML:
<TextView
...
android:autoLink="email" />
You can make your text clickable by using setOnClickListener on the text
textView.setOnClickListener(new View.OnClickListener());
You can open the email client by creating a new Intent with the ACTION_SEND. Settype, the email address and subject like this:
Intent emailintent = new Intent(android.content.Intent.ACTION_SEND);
emailintent.setType("plain/text");
emailintent.putExtra(android.content.Intent.EXTRA_EMAIL,new String[] {"mailk#gmail.com" });
emailintent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
emailintent.putExtra(android.content.Intent.EXTRA_TEXT,"");
startActivity(Intent.createChooser(emailintent, "Send mail..."));
You need to fire an intent in your onClickListener:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain"); // send email as plain text
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "some#email.address" });
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
startActivity(Intent.createChooser(intent, ""));
Please be aware of a little bug from API 24 onwards which makes the accepted solution not work if the local part of the email address has exactly 2 characters like "it#google.com".
See the issue: https://issuetracker.google.com/issues/64435698
Allegedly fixed already, but apparently not rolled out yet.
(Don't you love it that they know about the issue and don't even bother to update the documentation accordingly? https://developer.android.com/reference/android/widget/TextView.html#attr_android:autoLink)
So unless you're sure that you're not dealing with such 2-letter email addresses, you should rather use the accepted approach from here for the time being:
TextView to send email when clicked
Take care to remove the autolink attribute from the TextView then.
The accepted answer may work for emails but if you want to detect different patterns like emails, contact numbers, weblink and set a separate on click implementations for these patterns I suggest you to use CustomClickableEmailPhoneTextview
Sample Code to use the library.
CustomPartialyClickableTextview customPartialyClickableTextview= (CustomPartialyClickableTextview) findViewById(R.id.textViewCustom);
/**
* Create Objects For Click Patterns
*/
ClickPattern email=new ClickPattern();
ClickPattern phone=new ClickPattern();
ClickPattern weblink=new ClickPattern();
/**
* set Functionality for what will happen on click of that pattern
* In this example pattern is email
*/
email.setOnClickListener(new ClickPattern.OnClickListener() {
#Override
public void onClick() {
Toast.makeText(MainActivity.this,"email clicked",Toast.LENGTH_LONG).show();
}
});
/**
* set Functionality for what will happen on click of that pattern
* In this example pattern is phone
*/
phone.setOnClickListener(new ClickPattern.OnClickListener() {
#Override
public void onClick() {
Toast.makeText(MainActivity.this,"phone clicked",Toast.LENGTH_LONG).show();
}
});
/**
* set Functionality for what will happen on click of that pattern
* In this example pattern is weblink
*/
weblink.setOnClickListener(new ClickPattern.OnClickListener() {
#Override
public void onClick() {
Toast.makeText(MainActivity.this,"website clicked",Toast.LENGTH_LONG).show();
}
});
/**
* set respective regex string to be used to identify patter
*/
email.setRegex("\\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}\\b"); // regex for email
phone.setRegex("[1-9][0-9]{9,14}"); // regex for phone number
weblink.setRegex("^(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]"); // regex for weblink
/**
* add click pattern to the custom textview - first parameter is tag for reference second parameter is ClickPattern object
*/
customPartialyClickableTextview.addClickPattern("email",email);
customPartialyClickableTextview.addClickPattern("phone",phone);
customPartialyClickableTextview.addClickPattern("weblink",weblink);