Here i share my Android , React-Native , Kotlin coding knowledge for Android Beginner, Android Users, Android Developer. Kotlin android learners, React-Native learners. Also Support for Application developers with code suff to create applications.
Wednesday, 19 June 2019
Android 9 Pie Updates
Updated Android 9 (API level 28) introduce great new
features and capabilities for users and developers.
Some important features points are given below.
- Device Indoor positioning with Wi-Fi RTT
- support for the IEEE 802.11mc Wi-Fi protocol
- The device must have location services enabled and Wi-Fi
scanning turned on
- Need ACCESS_FINE_LOCATION permission
- Device Display cutout support
- lets you find out the location and shape of the
non-functional areas where content shouldn't be displayed.
- use the getDisplayCutout() method.
- attribute, layoutInDisplayCutoutMode, allows your app to
lay out its content around a device's cutouts.
- attribute
LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER
- Device Notifications Updated
Enhanced messaging
experience
- The Person class is used to identify people their avatars and URIs
- other APIs, such as addMessage()
- The Person class also supports the Builder design pattern.
- Device Channel settings, broadcasts, and Do Not Disturb
You can use the
isBlocked()
method
up settings
using the new
getNotificationChannelGroup()
method.NotificationManager
reference - Device now Multi-camera support and camera updates
ImageDecoder for drawables and bitmaps
- Device Animation
HDR VP9 Video, HEIF image compression, and Media APIs
supported in the
MediaMuxer
and MediaExtractor
classes- Device Data cost sensitivity in JobScheduler
- Device Neural Networks API 1.1
- Device having Autofill framework
- Device Security enhancements
- Device having Android Protected Confirmation
- Device having Hardware security module
- Device APK signature scheme with key rotation
- Device Option to allow key decryption only on unlocked devices
- Device have Legacy encryption support
- Device Deprecation of WPS
- Android backups
- Device Client-side encryption backups
- Define device conditions required for backup
- Accessibility
- Navigation semantics
- Accessibility pane titles
- Heading-based navigation
- Group navigation and output
- Window change details
- Rotation
- Text
- Power management
- Privacy changes
- Limited access to sensors in background
- Restricted access to call logs
Tuesday, 18 June 2019
How to get Device(Mobile) IME Number in Android Pro-grammatically
Need to add require permission in Android Manifest.xml file
Now need to Allow user permission at run time in your AppCompatActivity
public void FindIME() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// your READ_PHONE_STATE permission yet not granted.
DevicePermission();
} else {
// your READ_PHONE_STATE permission is already been granted.
ActivityCompat.requestPermissions(FlashScreen.this, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_READ_STATE);
GetIME();
}
}
Here we need to ask for user permission
private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
private void DevicePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
new AlertDialog.Builder(FlashScreen.this)
.setTitle("Permission Request")
.setMessage(getString(R.string.permission_read_phone_state_rationale))
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//re-request
ActivityCompat.requestPermissions(FlashScreen.this,
new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
})
.setIcon(R.drawable.ic_login)
.show();
} else {
// READ_PHONE_STATE permission has not been granted yet. Request it directly.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
}
public void GetIME() {
String deviceUniqueIdentifier = null;
TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
if (null != tm) {
deviceUniqueIdentifier = tm.getDeviceId();
}
if (null == deviceUniqueIdentifier || 0 == deviceUniqueIdentifier.length()) {
deviceUniqueIdentifier = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
}
IME_Device = deviceUniqueIdentifier;
Log.i("Device Ime", "Value--------->" + IME_Device);
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_PHONE_STATE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted!
GetIME();
} else {
// permission denied
Toast.makeText(mContext, "Need to allow Read Phone state ..", Toast.LENGTH_LONG).show();
}
}
break;
case PERMISSION_READ_STATE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted!
} else {
// permission denied
Toast.makeText(mContext, "Need to allow Read Phone state ..", Toast.LENGTH_LONG).show();
}
}
break;
}
}
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Now need to Allow user permission at run time in your AppCompatActivity
public void FindIME() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// your READ_PHONE_STATE permission yet not granted.
DevicePermission();
} else {
// your READ_PHONE_STATE permission is already been granted.
ActivityCompat.requestPermissions(FlashScreen.this, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_READ_STATE);
GetIME();
}
}
Here we need to ask for user permission
private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
private void DevicePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
new AlertDialog.Builder(FlashScreen.this)
.setTitle("Permission Request")
.setMessage(getString(R.string.permission_read_phone_state_rationale))
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//re-request
ActivityCompat.requestPermissions(FlashScreen.this,
new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
})
.setIcon(R.drawable.ic_login)
.show();
} else {
// READ_PHONE_STATE permission has not been granted yet. Request it directly.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
}
public void GetIME() {
String deviceUniqueIdentifier = null;
TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
if (null != tm) {
deviceUniqueIdentifier = tm.getDeviceId();
}
if (null == deviceUniqueIdentifier || 0 == deviceUniqueIdentifier.length()) {
deviceUniqueIdentifier = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
}
IME_Device = deviceUniqueIdentifier;
Log.i("Device Ime", "Value--------->" + IME_Device);
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_PHONE_STATE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted!
GetIME();
} else {
// permission denied
Toast.makeText(mContext, "Need to allow Read Phone state ..", Toast.LENGTH_LONG).show();
}
}
break;
case PERMISSION_READ_STATE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted!
} else {
// permission denied
Toast.makeText(mContext, "Need to allow Read Phone state ..", Toast.LENGTH_LONG).show();
}
}
break;
}
}
Device's Estimated Battery Time calculation
How to Calculate Android Estimated Battery Remaining Time.
within your AppCompatActivity
need to do register Battery change event listener with BroadcastReceiver like
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
Now you need to declare with Activity or where you need BroadcastReceiver
int expectedlevel;boolean isFirstAllow = true; int second; String strFirstTime,strSecondTime;private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context ctxt, Intent intent) { int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Calendar c = Calendar.getInstance(); if(isFirstAllow) { String formattedDate = format.format(c.getTime()); strFirstTime = formattedDate; expectedlevel = level - 1; isFirstAllow = false; second = new Time(System.currentTimeMillis()).getSeconds(); } if(!isFirstAllow && level == expectedlevel){ strSecondTime = format.format(c.getTime()); Date d1 = null; Date d2 = null; try { d1 = format.parse(strFirstTime); d2 = format.parse(strSecondTime); //in millisecondslong diff = d2.getTime() - d1.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000); System.out.print(diffDays + " days, "); System.out.print(diffHours + " hours, "); System.out.print(diffMinutes + " minutes, "); System.out.print(diffSeconds + " seconds."); // Now again we need percentage * difference time = total long time value. long totalMinues = diffMinutes * expectedlevel; long totalSecond = diffSeconds * expectedlevel; long converttoMinutes = totalSecond/60; long addedAllMinues = totalMinues + converttoMinutes; // Now convert total minitues to millisecond;long AllMillisond = addedAllMinues * 60000;// Now Again convert this total Millisond to hours,minutes, second// for Battery Hours; long FinaldiffSeconds = AllMillisond / 1000 % 60; long FinaldiffMinutes = AllMillisond / (60 * 1000) % 60; long FinaldiffHours = AllMillisond / (60 * 60 * 1000) % 24; long FinaldiffDays = AllMillisond / (24 * 60 * 60 * 1000); System.out.print(FinaldiffDays + " days, "); System.out.print(FinaldiffHours + " hours, "); System.out.print(FinaldiffMinutes + " minutes, "); System.out.print(FinaldiffSeconds + " seconds.");new AlertDialog.Builder(mcontext).setTitle("Battery Remaning Time") .setMessage(FinaldiffDays + " days, "+""+FinaldiffHours + " hours," + ""+""+FinaldiffMinutes + " minutes, "+FinaldiffSeconds + " seconds.") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Continue with delete operation } }) .setNegativeButton(android.R.string.no, null) .setIcon(android.R.drawable.ic_dialog_alert) .show();} catch (Exception e) {e.printStackTrace(); } } } };
Apply Multiple Permissions RunTime
How to give and apply run time multiple permissions in android,
First yo have to add permissions in Manifest file like below.
<uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
Then, you have to code for the check permissions,add button in activitymain.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical"
android:background="#e5ead3"
android:gravity="center" >
<Button
android:id="@+id/btn_do_task"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Permissions"
android:layout_gravity="center"/>
</LinearLayout>
After add button in xml file now add code in MainActivity.java file
import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.os.Build; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Context mContext; private Activity mActivity; private Button btn_checkpermi; private static final int MY_PERMISSIONS_REQUEST_CODE = 123; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = getApplicationContext(); mActivity = MainActivity.this; btn_checkpermi = findViewById(R.id.btn_checkpermi); btn_checkpermi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ checkPermission(); } } }); } protected void checkPermission(){ if(ContextCompat.checkSelfPermission(mActivity,Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission( mActivity,Manifest.permission.READ_CONTACTS) + ContextCompat.checkSelfPermission( mActivity,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ // when permissions not grantedif(ActivityCompat.shouldShowRequestPermissionRationale( mActivity,Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale( mActivity,Manifest.permission.READ_CONTACTS) || ActivityCompat.shouldShowRequestPermissionRationale( mActivity,Manifest.permission.READ_EXTERNAL_STORAGE)){ // If we should give explanation of requested permissions // Show an alert dialog for request explanationAlertDialog.Builder builder = new AlertDialog.Builder(mActivity); builder.setMessage("Camera, Read Contacts and Read External" + " Storage permissions are required to do the task."); builder.setTitle("Please grant those permissions"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener(){ @Overridepublic void onClick(DialogInterface dialogInterface, int i) { ActivityCompat.requestPermissions( mActivity, new String[]{ Manifest.permission.CAMERA, Manifest.permission.READ_CONTACTS, Manifest.permission.READ_EXTERNAL_STORAGE }, MY_PERMISSIONS_REQUEST_CODE ); } }); builder.setNeutralButton("Cancel",null); AlertDialog dialog = builder.create(); dialog.show(); }else{ // request directly required permissionsActivityCompat.requestPermissions( mActivity, new String[]{ Manifest.permission.CAMERA, Manifest.permission.READ_CONTACTS, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CODE ); } }else { // Do your stuff here, permissions are already grantedToast.makeText(mContext,"Permissions already granted",Toast.LENGTH_SHORT).show(); } } @Overridepublic void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){ switch (requestCode){ case MY_PERMISSIONS_REQUEST_CODE:{ // When request is cancelled, the results array are emptyif( (grantResults.length >0) && (grantResults[0] + grantResults[1] + grantResults[2] == PackageManager.PERMISSION_GRANTED ) ){ // Permissions are grantedToast.makeText(mContext,"Permissions granted.",Toast.LENGTH_SHORT).show(); }else { // Permissions are deniedToast.makeText(mContext,"Permissions denied.",Toast.LENGTH_SHORT).show(); } return; } } } }
How to Bitmap Compress reduce size and Compress format
Here you can reduce Bitmap Size and Compress in specific file format
Button click take Camera Picture in Fragment and Save on External Storage
Fragment
do with below Button Click code
After Intent pass, we can Create Bitmap from Uri Code within onActivityResult
// Now this Bitmap you can set as per need in Imageview imagePhoto
do with below Button Click code
mCamerabtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); if (checkPermission(wantCameraPermission)) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File file = new File(Environment.getExternalStorageDirectory(),"test.jpg"); outputFileUri = Uri.fromFile(file); Log.d("TAG", "outputFileUri intent" + outputFileUri); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivityForResult(intent, 111); } else { requestPermission(wantCameraPermission, PERMISSION_REQUEST_CODE_Camera); } dialog.cancel(); } });
Check for require permission above 6.0
private boolean checkPermission(String permission) {
if (Build.VERSION.SDK_INT >= 23) { int result = ContextCompat.checkSelfPermission(mcontext, permission); if (result == PackageManager.PERMISSION_GRANTED) { return true; } else { return false; } } else { return true; } }
private void requestPermission(String permission, int permission_requestcode) { requestPermissions(new String[]{permission}, permission_requestcode); }
@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grants) { List<Fragment> fragments = getChildFragmentManager().getFragments(); //==================Start switch (requestCode) { case PERMISSION_REQUEST_CODE_Camera: Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File file = new File(Environment.getExternalStorageDirectory(), "test.jpg"); outputFileUri = Uri.fromFile(file); Log.d("TAG", "outputFileUri intent" + outputFileUri); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); getActivity().startActivityForResult(intent, 111); break; case PERMISSION_REQUEST_CODE: if (grants.length > 0 && grants[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(mcontext, "Permission Granted. Now you can Read data.", Toast.LENGTH_LONG).show(); ImageLoad(); } else { Toast.makeText(mcontext, "Permission Denied. You cannot Read data.", Toast.LENGTH_LONG).show(); } break; } //================End if (fragments != null) { for (Fragment fragment : fragments) { if (fragment != null) { fragment.onRequestPermissionsResult(requestCode, permissions, grants); } } } }
After Intent pass, we can Create Bitmap from Uri Code within onActivityResult
@Overridepublic void onActivityResult(int reqCode, int resultCode, Intent data) { super.onActivityResult(reqCode, resultCode, data); switch (reqCode) { case 111:
Bitmap bitmap = decodeSampledBitmapFromUri(outputFileUri, 300, 400);if (resultCode == RESULT_OK) { Log.d("TAG", "outputFileUri RESULT_OK" + outputFileUri); if (outputFileUri != null) {
// Now this Bitmap you can set as per need in Imageview imagePhoto
imagePhoto.setImageBitmap(bitmap);
Here in below function we need to pass Uri, int reqWidth, int reqHeightbreak; }
}
public Bitmap decodeSampledBitmapFromUri(Uri uri, int reqWidth, int reqHeight) { Bitmap bm = null; try { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(((AppCompatActivity) mcontext).getContentResolver().openInputStream(uri), null, options); // Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false; bm = BitmapFactory.decodeStream(((AppCompatActivity) mcontext).getContentResolver().openInputStream(uri), null, options); } catch (FileNotFoundException e) { e.printStackTrace(); Toast.makeText(mcontext, e.toString(), Toast.LENGTH_LONG).show(); } return bm; }
Subscribe to:
Posts (Atom)
Find Hours Diffrence in Kotlin
In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...
-
Auro InfoSoft built the Diwali Dhamaka app as a Free app. This SERVICE is provided by Auro InfoSoft at no cost and is intended for use as ...
-
Auro InfoSoft built the Thanksgiving Day Wallpapers app as a Free app. This SERVICE is provided by Auro InfoSoft at no cost and is intende...
-
Auro InfoSoft built the Visiting Cards Real app as a Free app. This SERVICE is provided by Auro InfoSoft at no cost and is intended for us...