Google map for android my location custom button

With a simple trick, you can replace the my location button with a custom one.

  1. Customize the Layout of your new button.
  2. Set my location enabled in maps api.
  3. Hide default button of my location.
  4. call click method of my location on your custom button click.

1. Customize the layout of your new button

add a new button to your desired location in layout file of map activity.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:map="http://schemas.android.com/apk/res-auto"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_height="match_parent"
     android:layout_width="match_parent">

    <fragment
         android:id="@+id/map"
         android:name="com.google.android.gms.maps.SupportMapFragment"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         tools:context=".activities.MapsActivity" />

   <ImageView
        android:id="@+id/ic_location"
        android:layout_width="18dp"
        android:layout_height="18dp"
        android:src="@drawable/ic_location"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="18dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"/>
</RelativeLayout>

2. Set my location enabled in maps api

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // Enable My Location
    mMap.setMyLocationEnabled(true);
    /* and DON'T disable the default location button*/
 }

3. Hide default button of my location.

 //Create field for map button.
    private View locationButton;

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMyLocationEnabled(true);

        // get your maps fragment
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
        // Extract My Location View from maps fragment 
        locationButton = mapFragment.getView().findViewById(0x2);
        // Change the visibility of my location button
        if(locationButton != null)
            locationButton.setVisibility(View.GONE);
    }

4. call click method of my location on your custom button click.

findViewById(R.id.ic_location).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mMap != null)
            {
                if(locationButton != null)
                    locationButton.callOnClick();

            }
         }
    });

Fatal Android 12: Exception: startForegroundService() not allowed due to mAllowStartForeground false

Previously we were using Service to run background tasks such as backup of data, setting up reminder notifications etc. And the code for invoking the service earlier will be as follows

Intent serviceIntent = new Intent ( context, BackupService.class );
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    OneTimeWorkRequest request = new OneTimeWorkRequest.Builder ( BackupWorker.class ).addTag ( "BACKUP_WORKER_TAG" ).build ();
    WorkManager.getInstance ( context ).enqueue ( request );
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    context.startForegroundService ( serviceIntent );
} else {
    context.startService ( serviceIntent );
}

Sample code for BackupService (Existing).

public class BackupService extends Service {

    private static final String TAG = "BackupService";

    @Nullable
    @Override
    public IBinder onBind ( Intent intent ) {
        return null;
    }

    @Override
    public int onStartCommand ( Intent intent, int flags, int startId ) {
        Log.d ( TAG, "onStartCommand" );
        startForeground ( BACKUP_SERVICE_NOTIFICATION_ID, createServiceNotification () );
        //call methods to perform background task
        return super.onStartCommand ( intent, flags, startId );
    }
}

Sample code for BackupWorker (Newly added).

public class BackupWorker extends Worker {

    private static final String TAG = "BackupWorker";

    public BackupWorker ( @NonNull Context context, @NonNull WorkerParameters workerParams ) {
        super ( context, workerParams );
    }

    @NonNull
    @Override
    public Result doWork () {
        //call methods to perform background task
        return Result.success ();
    }
}

Make sure to add the following dependencies in the module-level gradle file

implementation 'androidx.work:work-runtime:2.7.1'
implementation 'com.google.guava:guava:27.0.1-android'

I have tested the above code working with Android 5, Android 8, Android 11 & Android 12. Working as expected in my case.

Hope this solution helps someone who is targeting their application for SDK 31 / Android 12+.

samsung s10 plus dual messenger not working after android x(10)

      • Go to the Recovery Mode

      galaxy s10 recovery modeFirst, you need to boot your Samsung S10 into stock recovery mode. To do this step, you can turn off your phone first. Then, press and hold the Volume up, Bixby, and Power buttons simultaneously. Wait until you see an android logo.

    • Choose Wipe Cache Partition

    galaxy s10 wipe dataFrom the recovery mode, you will see some options. Then, you are allowed to select the option of “Wipe cache partition”. To go to this choice, you can use the volume button to navigate. To choose the option you want, you can use the power button.

    • Reboot your Phone and it’s Done

    After you click on the “Wipe cache partition”, the cache on your Samsung Galaxy S10 will be removed. So, just reboot your device and now your phone is free from the unused cache.

 

Bluetooth printer for Android

For enabling bluetooth there is no dependency or anything needed just follow the below steps.

AndroidManifest.xml

Add the below Java file in your application.BluetoothPrinter .Java

public class BluetoothPrinter {

public static final int ALIGN_CENTER = 100;
public static final int ALIGN_RIGHT = 101;
public static final int ALIGN_LEFT = 102;

private static final byte[] NEW_LINE = {10};
private static final byte[] ESC_ALIGN_CENTER = new byte[]{0x1b, 'a', 0x01};
private static final byte[] ESC_ALIGN_RIGHT = new byte[]{0x1b, 'a', 0x02};
private static final byte[] ESC_ALIGN_LEFT = new byte[]{0x1b, 'a', 0x00};

private BluetoothDevice printer;
public static BluetoothSocket btSocket = null;
private OutputStream btOutputStream = null;

public BluetoothPrinter(BluetoothDevice printer) {
this.printer = printer;
}

public void connectPrinter(final PrinterConnectListener listener) {
new ConnectTask(new ConnectTask.BtConnectListener() {
@Override
public void onConnected(BluetoothSocket socket) {
btSocket = socket;
try {
btOutputStream = socket.getOutputStream();
listener.onConnected();
} catch (IOException e) {
listener.onFailed();
}
}

@Override
public void onFailed() {
listener.onFailed();
}
}).execute(printer);
}

public boolean isConnected() {
return btSocket != null && btSocket.isConnected();
}

public void finish() {
if (btSocket != null) {
try {
btOutputStream.close();
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
btSocket = null;
}
}

public boolean printText(String text) {
try {
btOutputStream.write(encodeNonAscii(text).getBytes());
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

public boolean printUnicode(byte[] data) {
try {
btOutputStream.write(data);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

public boolean printLine() {
return printText("________________________________");
}

public boolean addNewLine() {
return printUnicode(NEW_LINE);
}

public int addNewLines(int count) {
int success = 0;
for (int i = 0; i < count; i++) {
if (addNewLine()) success++;
}

return success;
}

public boolean printImage(Bitmap bitmap) {
byte[] command = decodeBitmap(bitmap);
return printUnicode(command);
}

public void setAlign(int alignType) {
byte[] d;
switch (alignType) {
case ALIGN_CENTER:
d = ESC_ALIGN_CENTER;
break;
case ALIGN_LEFT:
d = ESC_ALIGN_LEFT;
break;
case ALIGN_RIGHT:
d = ESC_ALIGN_RIGHT;
break;
default:
d = ESC_ALIGN_LEFT;
break;
}

try {
btOutputStream.write(d);
} catch (IOException e) {
e.printStackTrace();
}
}

public void setLineSpacing(int lineSpacing) {
byte[] cmd = new byte[]{0x1B, 0x33, (byte) lineSpacing};
printUnicode(cmd);
}

public void setBold(boolean bold) {
byte[] cmd = new byte[]{0x1B, 0x45, bold ? (byte) 1 : 0};
printUnicode(cmd);
}

public void feedPaper() {
addNewLine();
addNewLine();
addNewLine();
addNewLine();
}

private static class ConnectTask extends AsyncTask<BluetoothDevice, Void, BluetoothSocket> {
private BtConnectListener listener;

private ConnectTask(BtConnectListener listener) {
this.listener = listener;
}

@Override
protected BluetoothSocket doInBackground(BluetoothDevice... bluetoothDevices) {
BluetoothDevice device = bluetoothDevices[0];
UUID uuid = device.getUuids()[0].getUuid();
BluetoothSocket socket = null;
boolean connected = true;

try {
socket = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
}
try {
socket.connect();
} catch (IOException e) {
try {
socket = (BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[]{int.class})
.invoke(device, 1);
socket.connect();
} catch (Exception e2) {
connected = false;
}
}

return connected ? socket : null;
}

@Override
protected void onPostExecute(BluetoothSocket bluetoothSocket) {
if (listener != null) {
if (bluetoothSocket != null) listener.onConnected(bluetoothSocket);
else listener.onFailed();
}
}

private interface BtConnectListener {
void onConnected(BluetoothSocket socket);

void onFailed();
}
}

public interface PrinterConnectListener {
void onConnected();

void onFailed();
}

private static String encodeNonAscii(String text) {
return text.replace('á', 'a')
.replace('č', 'c')
.replace('ď', 'd')
.replace('é', 'e')
.replace('ě', 'e')
.replace('í', 'i')
.replace('ň', 'n')
.replace('ó', 'o')
.replace('ř', 'r')
.replace('š', 's')
.replace('ť', 't')
.replace('ú', 'u')
.replace('ů', 'u')
.replace('ý', 'y')
.replace('ž', 'z')
.replace('Á', 'A')
.replace('Č', 'C')
.replace('Ď', 'D')
.replace('É', 'E')
.replace('Ě', 'E')
.replace('Í', 'I')
.replace('Ň', 'N')
.replace('Ó', 'O')
.replace('Ř', 'R')
.replace('Š', 'S')
.replace('Ť', 'T')
.replace('Ú', 'U')
.replace('Ů', 'U')
.replace('Ý', 'Y')
.replace('Ž', 'Z');
}

public static byte[] decodeBitmap(Bitmap bmp) {
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();

List list = new ArrayList<>();
StringBuffer sb;
int zeroCount = bmpWidth % 8;
String zeroStr = "";
if (zeroCount > 0) {
for (int i = 0; i < (8 - zeroCount); i++) zeroStr = zeroStr + "0";
}

for (int i = 0; i < bmpHeight; i++) {
sb = new StringBuffer();
for (int j = 0; j < bmpWidth; j++) { int color = bmp.getPixel(j, i); int r = (color >> 16) & 0xff;
int g = (color >> 8) & 0xff;
int b = color & 0xff;
if (r > 160 && g > 160 && b > 160) sb.append("0");
else sb.append("1");
}
if (zeroCount > 0) sb.append(zeroStr);
list.add(sb.toString());
}

List bmpHexList = binaryListToHexStringList(list);
String commandHexString = "1D763000";
String widthHexString = Integer
.toHexString(bmpWidth % 8 == 0 ? bmpWidth / 8 : (bmpWidth / 8 + 1));
if (widthHexString.length() > 2) {
return null;
} else if (widthHexString.length() == 1) {
widthHexString = "0" + widthHexString;
}
widthHexString = widthHexString + "00";

String heightHexString = Integer.toHexString(bmpHeight);
if (heightHexString.length() > 2) {
return null;
} else if (heightHexString.length() == 1) {
heightHexString = "0" + heightHexString;
}
heightHexString = heightHexString + "00";

List commandList = new ArrayList<>();
commandList.add(commandHexString + widthHexString + heightHexString);
commandList.addAll(bmpHexList);

return hexList2Byte(commandList);
}

private static List binaryListToHexStringList(List list) {
List hexList = new ArrayList<>();
for (String binaryStr : list) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < binaryStr.length(); i += 8) {
String str = binaryStr.substring(i, i + 8);
String hexString = strToHexString(str);
sb.append(hexString);
}
hexList.add(sb.toString());
}
return hexList;
}

private static String hexStr = "0123456789ABCDEF";
private static String[] binaryArray = {"0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"};

private static String strToHexString(String binaryStr) {
String hex = "";
String f4 = binaryStr.substring(0, 4);
String b4 = binaryStr.substring(4, 8);
for (int i = 0; i < binaryArray.length; i++) {
if (f4.equals(binaryArray[i]))
hex += hexStr.substring(i, i + 1);
}
for (int i = 0; i < binaryArray.length; i++) {
if (b4.equals(binaryArray[i]))
hex += hexStr.substring(i, i + 1);
}

return hex;
}

private static byte[] hexList2Byte(List list) {
List<byte[]> commandList = new ArrayList<>();
for (String hexStr : list) commandList.add(hexStringToBytes(hexStr));
return sysCopy(commandList);
}

private static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) return null;
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}

private static byte[] sysCopy(List<byte[]> srcArrays) {
int len = 0;
for (byte[] srcArray : srcArrays) {
len += srcArray.length;
}
byte[] destArray = new byte[len];
int destLen = 0;
for (byte[] srcArray : srcArrays) {
System.arraycopy(srcArray, 0, destArray, destLen, srcArray.length);
destLen += srcArray.length;
}

return destArray;
}

private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}

public BluetoothSocket getSocket() {
return btSocket;
}

public BluetoothDevice getDevice() {
return printer;
}
}

And finally, add the below line of code where we want to print.

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice mBtDevice = btAdapter.getBondedDevices().iterator().next(); // Get first paired device

final BluetoothPrinter mPrinter = new BluetoothPrinter(mBtDevice);
mPrinter.connectPrinter(new BluetoothPrinter.PrinterConnectListener() {

@Override
public void onConnected() {
mPrinter.setAlign(BluetoothPrinter.ALIGN_CENTER);
mPrinter.printText("Hello World!");
mPrinter.addNewLine();

mPrinter.finish();
}

@Overide
public void onFailed() {
Log.d("BluetoothPrinter", "Conection failed");
}

});

Android – Create new Contact Programmatically

Step 1:

Add permission in Manifest.xml

<uses-permission android:name="android.permission.WRITE_CONTACTS" />
Step 2:
In java code

public void WritePhoneContact(String displayName, String number, Context cntx /*App or Activity Ctx*/) {
    Context contetx = cntx; //Application's context or Activity's context
    String strDisplayName = displayName; // Name of the Person to add
    String strNumber = number; //number of the person to add with the Contact
    System.out.println("NAME ====> " + strDisplayName + "    NUMBER ====>  " + strNumber);
    ArrayList<ContentProviderOperation> cntProOper = new ArrayList<ContentProviderOperation>();
    int contactIndex = cntProOper.size();//ContactSize

    //Newly Inserted contact
    // A raw contact will be inserted ContactsContract.RawContacts table in contacts database.
    cntProOper.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)//Step1
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());

    //Display name will be inserted in ContactsContract.Data table
    cntProOper.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)//Step2
            .withValueBackReference(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, contactIndex)
            .withValue(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, strDisplayName) // Name of the contact
            .build());
    //Mobile number will be inserted in ContactsContract.Data table
    cntProOper.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)//Step 3
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, contactIndex)
            .withValue(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, strNumber) // Number to be added
            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build()); //Type like HOME, MOBILE etc
    try {
        // We will do batch operation to insert all above data
        //Contains the output of the app of a ContentProviderOperation.
        //It is sure to have exactly one of uri or count set
        ContentProviderResult[] contentProresult = null;
        contentProresult = contetx.getContentResolver().applyBatch(ContactsContract.AUTHORITY, cntProOper); //apply above data insertion into contacts list
    } catch (RemoteException exp) {
        //logs;
    } catch (OperationApplicationException exp) {
        //logs
    }
}

My Nexus device won’t charge or turn on

First, do these quick checks:

Method 1:

  • Make sure the power outlet your Nexus device is plugged into is working properly.
  • Make sure you’re using the power adapter and USB cable that came with your Nexus device. Check to make sure that this charger is working correctly by trying it with another device.
  • Make sure there isn’t any dust or lint in the power port. The inside of the port should look like this:
  • Make sure the power cord is securely connected to the device and the power adapter.

After you’ve plugged your device in:

  1. Check to see if a battery icon appears on the screen after 1 minute.
  2. If the battery icon appears, press and hold the Power button for 15 to 30 seconds to see if your device turns on.

Method : 2:

  1. Unplug the USB cable from the power adapter and use it to connect your Nexus device to a computer’s USB port while the computer is on and connected to a power source.
  2. After 10-15 minutes, disconnect the USB cable from your Nexus device and reconnect it within 10 seconds.
  3. After 1 minute, check to see if a battery icon appears on the screen.
  4. Press & hold the Power button for at least 15 seconds to see if your device turns on.

Get Configured Email Address From Android Device Programmatically

In java code need the following piece of code.

String gmail = null;

    Pattern gmailPattern = Patterns.EMAIL_ADDRESS; // API level 8+

    Account[] accounts = AccountManager.get(this).getAccounts();

    for (Account account : accounts) {

        if (gmailPattern.matcher(account.name).matches()) {

            gmail = account.name;

        }

    }

    Log.d(“gmail”, gmail+“**”);

And also need permission in AndroidManifest.xml

<uses-permission android:name=“android.permission.GET_ACCOUNTS” />

Get Configured Email Address From Android Device Programmatically

In java code need the following piece of code.

String gmail = null;

    Pattern gmailPattern = Patterns.EMAIL_ADDRESS; // API level 8+

    Account[] accounts = AccountManager.get(this).getAccounts();

    for (Account account : accounts) {

        if (gmailPattern.matcher(account.name).matches()) {

            gmail = account.name;

        }

    }

    Log.d(“gmail”, gmail+“**”);

And also need permission in AndroidManifest.xml

<uses-permission android:name=“android.permission.GET_ACCOUNTS” />

Hide and Unhide Application in HomeScreen Android

For Hide application icon:

PackageManager p = getPackageManager();
ComponentName componentName = new ComponentName(this, com.apps.MainActivity.class); // activity which is first time open in manifiest file which is declare as <category android:name="android.intent.category.LAUNCHER" />
p.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

For Unhide Application:

PackageManager p = getPackageManager();
ComponentName componentName = new ComponentName(this, com.apps.MainActivity.class);
p.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

Known Issue:

After hide application your Activity will destroyed. So trying to start my main activity but its giving me ActivityNotFoundException.

Solution:

After hide you MainActivity once you hide it the activity will not be found it’s destroy so you need to create same another activity like mainActivity2 and you need to store boolean value to sharerdprefrence that whether icon is hiddne then u need to open mainActivity2 else MainActivity