Displaying contacts with EMAIL address only in android - email

i am trying to build a app, where phone contacts only with email address has to be displayed to the user.When the user click on the editbox in my app,phone contacts only with email address has to be displayed,after the user selects a contact, the email address of that contact has to be sent back to my app, which i use it further in my app.
//this is my code under onActivityResult() method
try
{
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Email.CONTENT_URI, null, Email.CONTACT_ID + "=?", new String[] { id }, null);
emailIdx = cursor.getColumnIndex(Email.DATA);
if (cursor.moveToFirst())
{
while (cursor.isAfterLast() == false)
{
emailid = cursor.getString(emailIdx);
allids.add(emailid);
cursor.moveToNext();
}
}
else
{
//no results actions
}
}
// This is the intent i am passing.
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Email.ADDRESS);
startActivityForResult(intent, 1);
// manifest permissions.
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<intent-filter>
<action android:name="android.intent.action.PICK" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.cursor.dir/email_v2" />
<data android:mimeType="vnd.android.cursor.item/email_v2" />
</intent-filter>
i am getting the below error when i try to run my app.
android.content.ActivityNotFoundException: No Activity found to handle Intent {act=android.intent.action.PICK typ=data1 }
I am not sure of what could be the problem, am i missing something in the manifest.xml?.please help.
Thanks!

This is quite old now but if I was searching for it I'm sure others are too so here's my solution. The intent is launched as follows:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.Email.CONTENT_TYPE);
startActivityForResult(intent, RC_GET_EMAIL);
Then to get the email address from the picked contact:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RC_GET_EMAIL) {
if(resultCode == Activity.RESULT_OK) {
Uri contactUri = data.getData();
String[] projection = new String[]{ContactsContract.CommonDataKinds.Email.DATA};
Cursor cursor = getContext().getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if(cursor.moveToFirst()) {
int emailIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
String email = cursor.getString(emailIndex);
// do something with email
}
cursor.close();
}
}
}
}
Remember that for Marshmallow and above you will need to manually request the READ_CONTACTS permission in order to do anything meaningful.

Put the below code in the listener, hope this helps.
Code
Intent intent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);

Related

Scoped Storage won't allow FileInputStream access to file in DOWNLOADS, is there a workaround?

I import data from a downloaded spreadsheet into a Room database. This is what I need to do :
String filePath = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath();
String fileName = context.getString(R.my_file_name);
File importFile = new File(filePath + File.separator, fileName);
try {
FileInputStream stream = new FileInputStream(importFile);
// do stuff
} catch (Exception e1) {e1.printStackTrace();}
So, this doesn't work anymore(?) I haven't been able to find a concise explanation (in JAVA) of how to accomplish this simple operation going forward without asking for the MANAGE_EXTERNAL_STORAGE permission (an unacceptable solution) Help from the gurus?
So, need to set up intent in manifest, and leave old permissions for legacy android
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
<application
android:requestLegacyExternalStorage="true"
>
<activity
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
in mainActivity, set up file picker, create method to launch the picker, and create method to process picker result.
Main Activity :
private ActivityResultLauncher<Intent> launchFilePicker;
public File importFile;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filePath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).
getAbsolutePath();
launchFilePicker = registerForActivityResult(
new ActivityResultContract<Intent, Uri>() {
#NonNull
#Override
public Intent createIntent(#NonNull Context context, Intent input) {
return input;
}
#Override
public Uri parseResult(int resultCode, #Nullable Intent result) {
if (result == null || resultCode != Activity.RESULT_OK) {
return null;
}
return result.getData();
}
},
this::getFileFromUri);
...
public void launchFileFinder() {
Intent pickerIntent = new Intent(ACTION_OPEN_DOCUMENT);
pickerIntent.addCategory(Intent.CATEGORY_OPENABLE);
pickerIntent.setType(" your mime type ");
pickerIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
launchFilePicker.launch(pickerIntent);
}
...
public void getFileFromUri(Uri result) {
String fileName = context.getString(R.my_file_name);
File importFile = new File(filePath + File.separator, fileName);
InputStream stream = null;
try {
stream = AppMainActivity.this.getContentResolver().openInputStream(result);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (stream != null) {
try {
FileInputStream stream = new FileInputStream(importFile);
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
}
}
}
}

Display specific Activity, when Firebase notification is tapped

When user taps on a notification sent from the Firebase console, I need to launch a specific Android Activity, only when the user taps on the notification. How can this be accomplished in the following 2 scenarios:
App is not opened or app running in Background
App is in the foreground
You can achieve this in two ways,
1. First way
Adding click_action in notification payload,
jNotification.put("click_action", "OPEN_ACTIVITY_1");
private void pushNotification(String token) {
JSONObject jPayload = new JSONObject();
JSONObject jNotification = new JSONObject();
JSONObject jData = new JSONObject();
try {
jNotification.put("title", "Google I/O 2016");
jNotification.put("text", "Firebase Cloud Messaging (App)");
jNotification.put("sound", "default");
jNotification.put("badge", "1");
jNotification.put("click_action", "OPEN_ACTIVITY_1");
jData.put("picture_url", "http://opsbug.com/static/google-io.jpg");
jPayload.put("to", token);
//jPayload.put("to", "/topics/news");
//jPayload.put("condition", "'logined' in topics || 'news' in topics");
//jPayload.put("registration_ids", jData);
jPayload.put("priority", "high");
jPayload.put("notification", jNotification);
jPayload.put("data", jData);
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", AUTH_KEY);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
// Send FCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jPayload.toString().getBytes());
// Read FCM response.
InputStream inputStream = conn.getInputStream();
final String resp = convertStreamToString(inputStream);
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
#Override
public void run() {
Log.e("Response", resp);
//txtStatus.setText(resp);
}
});
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
Add this is in your AndroidManifest.xml
<activity android:name="com.example.fcm.SecondActivity">
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
RemoteMessage.Notification notification = remoteMessage.getNotification();
Map<String, String> map = remoteMessage.getData();
sendNotification(notification.getTitle(), notification.getBody(), map);
}
private void sendNotification(String title, String body, Map<String, String> map) {
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setContentInfo(title)
.setLargeIcon(icon)
.setSmallIcon(R.mipmap.ic_launcher);
try {
String picture_url = map.get("picture_url");
if (picture_url != null && !"".equals(picture_url)) {
URL url = new URL(picture_url);
Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(body));
}
} catch (IOException e) {
e.printStackTrace();
}
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setLights(Color.YELLOW, 1000, 300);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private static final String TAG = "SecondActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
for (String key : bundle.keySet()) {
Object value = bundle.get(key);
Log.d(TAG, "Key: " + key + " Value: " + value.toString());
}
}
}
}
2. Second way
Send key through data payload like below and get key in MainActivity via getIntent() and call specific activity or fragments.
json1.put("title","Your Title");
json1.put("body","body content");
json1.put("message","Your Message");
json1.put("screen","2"); //secondFragment is 2nd position in nav drawer
json.put("data", json1);
MainActivity.java
Intent intent = getIntent();
String pos = getIntent().getStringExtra("screen");
if(pos !=null){
selectDrawerItem(navigationView.getMenu().getItem(Integer.parseInt(pos)));
}
Sample project in GITHUB,
https://github.com/Google-IO-extended-bangkok/FCM-Android

azure push notifications on Android

I am triying to send push notifications on Android and iOS using azure mobile services (not hubs)
For iOS push notifications are working fine, I get the deviceToken and send a push to that devide
On Android I get the registration ID and send a push, But I dont get anything on the device:
My permissions:
<!-- GCM connects to Google Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!--
Creates a custom permission so only this app can receive its messages.
NOTE: the permission *must* be called PACKAGE.permission.C2D_MESSAGE,
where PACKAGE is the application's package name.
-->
<permission android:name="com.sebiz.x_blockerEx.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.sebiz.x_blockerEx.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- This app has permission to check your contacts -->
<uses-permission android:name="android.permission.READ_CONTACTS" />
<!-- Needed for MobileAppTracking SDK -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> ....
I got the receiver
<receiver android:name="com.microsoft.windowsazure.notifications.NotificationsBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.sebiz.blockerEx" />
</intent-filter>
</receiver>
Also the Handler code:
#Override
public void onReceive(Context context, Bundle bundle) {
ctx = context;
String nhMessage = bundle.getString("message");
sendNotification(nhMessage);
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
new Intent(ctx, ACT_Home.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("ALERTA")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
The push script for android...
if (action == "Unblock") {
var payload = "¡Pronto! Tienes que ayudar a " + userName + ", esta a punto de caer. ¡Llámale!";
var pushId = results[0].deviceToken;
console.log("Sending the push notification for unblock to device..." + results[0].deviceToken);
if (results[0].device == 'android') {
push.gcm.send(pushId, "¡Pronto! Tienes que ayudar a " + userName + ", esta a punto de caer. ¡Llámale!", {
success: function(pushResponse) {
console.log("Sent push:", pushResponse, payload);
},
error: function (pushResponse) {
console.log("Error Sending push:", pushResponse);
}
});
}
else if( results[0].device == 'iPhone'){
var dtoken = results[0].deviceToken;
push.apns.send(dtoken, {
alert: "¡Pronto! Tienes que ayudar a " + userName +", esta a punto de caer. ¡Llámale!",
payload: {
"inAppMessage" : "¡Pronto! Tienes que ayudar a " + userName +", esta a punto de caer. ¡Llámale!"
},
error: function(error) {
console.log('Error sending push notification: ', error);
}
});
}
}
So i use the registrationid on andorid to send push to device and the AZURE console says it did send the push:
INFORMATION Sent push: { multicast_id: 5869048580698496000, success:
1, failure: 0, canonical_ids: 0, results: [ { message_id:
'0:1421340390672415%29c0b12cf9fd7ecd' } ], invalidIds: [],
updatedIds: {} } ¡Pronto! Tienes que ayudar a ..., esta a punto de
caer. ¡Llámale!
Code to conect to mobile service:
try {
mClient = new MobileServiceClient(
"https://bloqueatuex.azure-mobile.net/",
"**********", //I put *** so i do not make my key public
this
).withFilter(new ProgressFilter());
//mUsersTable = mClient.getTable("users", usersAzure.class);
Log.i(TAG,"MS_Azure_INITIALIZE" +"FRESH INITIALIZED");
//fetchUserDetailsandInsertToAzure(Session.openActiveSession(ACT_Home.this, true, callback));
//Log.e("AZURE","azure_InsertedUserData: TRUE");
NotificationsManager.handleNotifications(this, SENDER_ID, azureHandler.class);
} catch (MalformedURLException e)
{
Log.e(TAG,"MS_Azure_ " +e.getMessage());
}
On the handler:
public class azureHandler extends com.microsoft.windowsazure.notifications.NotificationsHandler {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
#Override
public void onRegistered(Context context, final String gcmRegistrationId) {
super.onRegistered(context, gcmRegistrationId);
ctx = context;
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
try {
if (ACT_CheckAge.mClient != null) {
ACT_CheckAge.mClient.getPush().register(gcmRegistrationId, null);
}
return null;
} catch (Exception e) {
Log.e("AZURE", "Error en registro con gcm...error:"+ e);
}
return null;
}
}.execute();
}
Any Help will be greatly appreciated
Well it turnout that it works on Android 4.2+
I was testing on Android 4.0, I do not know why it doesnt work on that version since the phone does get notifications from other apps, but after testing in 4.2 and 4.4 the notifications work fine.
Hope that helps others with the same problems
If in the server you send:
push.gcm.send(pushId, message);
You have to register the pushId target in your APP handler:
CT_CheckAge.mClient.getPush().register(gcmRegistrationId, pushId);
In APP handler, pushId have to be String[].

Email sending in Spring batch

I am very new to Spring batch. I have a requirement to send mail from my application after processing some records. Went through many links. But i did not find anything useful. Can somebody help me?
Hi You can try below code, I am using this javax code in my project and working cool..
public void sendMailtoMgr(final String subject, final String message,
String mgrmailIds) {
String mngrecipients = null;
Message msg = null;
InternetAddress[] mgraddress = null;
boolean debug = false;
try {
// Load your SMTP Properties from Property file
Properties props = new Properties();
props.put(SMTP_HOST, SMTP_HOST_VALUE);
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
msg = new MimeMessage(session);
// From value is nothing but from Address , can give your email id
msg.setFrom(new InternetAddress(SMTP_FROM_VALUE));
mngrecipients = mgrmailIds;
mgraddress = addRecipients(mngrecipients);
if (mgraddress != null && mgraddress.length != 0) {
msg.setRecipients(Message.RecipientType.TO, mgraddress);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setSubject(subject);
msg.setContent(message, "text/html");
Transport.send(msg);
}
}
catch (MessagingException mex) {
logger.info("Exception in sendMail()");
mex.printStackTrace();
}
catch (Exception e) {
logger.info("Exception in sendMail()", e);
} finally {
logger.info("Exiting sendMail()");
}
}
You need to implement a JobExecutionListener and add it to your job in the following manner:
<batch:job id="provisionAddOns" >
<batch:step id="cpsProvisionAddOns">
...
</batch:step>
<batch:listeners>
<batch:listener>
<bean class="EmailNotification" />
</batch:listener>
</batch:listeners>
</batch:job>
Here EmailNotification implements JobExecutionListener and send the email in the afterJob() method; you can use any method you like to send emails depending on your needs.

Display image capture using camera in android device

i want's to display image capture using device camera and for that i have used below code.but i am getting null value in data that is return in onActivityResult .so please provide me solution for that..
thanks,
and my code is:
File root = new File(Environment.getExternalStorageDirectory()+"/TestCameraGallery");
root.mkdirs();
MyCameraGallery = new File(root, "mycamerapicname");
Uri outputFileUri = Uri.fromFile(MyCameraGallery );
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_PIC_REQUEST)
{
Uri uri = data.getData();
}
}
value of uri is null and give null pointer exception so please help me
Using your code you will get low resolution image. If you wanna get the high resolution image you can refer this answer.
And also you can refer this blog
get solution finally
String imageName = "image.jpg" ;
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, imageName);
uri_captureImage = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri_captureImage);
startActivityForResult(intent, requestCode_camera);
and in onAcitivity for result
String[] projection = new String[] {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri_captureImage, projection, null, null, null);
cursor.moveToFirst();
String capimage_path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));