Sunday, 24 December 2017

SMS BroadcastReceiver, Reading Complete SMS


Using BroadcastReceiver, allows the system to get alert whenever a message received. Upon message reception, you can handle as per requirement. A message may be composed of multi-parts, so, you can combine it and show as a single complete message. Following is the onReceive method:

@Override
public void onReceive(Context context, Intent intent) {        
    
    // Get the data (SMS data) bound to intent
    StringBuilder text=new StringBuilder();
    
    // Retrieves a map of extended data from the intent.    
    final Bundle bundle = intent.getExtras();
    Log.d(TAG, "onReceive");
    try {

        if (bundle != null) {

            final Object[] pdusObj = (Object[]) bundle.get("pdus");

            for (int parts = 0; parts < pdusObj.length; parts++) {
                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[parts]);
                String senderNumber = currentMessage.getDisplayOriginatingAddress();
                String message = currentMessage.getDisplayMessageBody();

                Log.i("SmsReceiver", "senderNumber: "+ senderNumber + "; message: " + message);
                text.append(message); //combine sms parts as a single message            } // end for loop

            // Show Alert            
            Toast.makeText(context, "Complete Message: " +text.toString() , Toast.LENGTH_LONG).show();
        } // bundle is null
    } catch (Exception e) {

        Log.e("SmsReceiver", "Exception smsReceiver" +e);
    }
 }

Handling Permission and Sending SMS

SMS sending and receiving is simple but due to advancements in permissions since Marshmallow version it needs special permission(s) to be requested runtime. Then user may or may not grant these permission(s). Earlier versions do not require permission(s) on app launch or at runtime.  Therefore, we need to take care of permission(s), depending on the version of the phone.

To request permission, we define method in the main activity as follow:

public class MainActivity extends AppCompatActivity {

@Overrideprotected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    requestSMSPermission();

    if(isSMSPermitted()){
         //Get the default instance of SmsManager         
         SmsManager smsManager = SmsManager.getDefault();
         String mobileNumber = "92xxxxxxxx"; //enter mobile number
         String smsBody = " Hi, this is a test SMS, Cheers!";
         short port = 6734;
         //Send a text SMS
         SmsManager.getDefault().sendTextMessage(phoneNumber, null, smsBody, null, null);
    }
}

/** * Request SMS permission runtime */private void requestSMSPermission() {

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
            Manifest.permission.READ_SMS)) {

        //https://developer.android.com/training/permissions/requesting.html    }
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS},
            SMS_PERMISSION_REQ_CODE);
  }

  //Handle Permission Result 
  @Override 
  public void onRequestPermissionsResult(int requestCode,
                                        String permissions[], int[] results) {

     switch (requestCode) {

         case SMS_PERMISSION_REQ_CODE: {

             if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) {

                 // permission granted
                 Toast.makeText(MainActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();

             } else {

                 // permission denied
                 Toast.makeText(MainActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();
             }
             return;
           }
        }
    }
   /** * Check if SMS permission granted */
   public boolean isSMSPermitted() {

    return ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED;
  }
}




Wednesday, 23 November 2016

Install / Uninstall App from Another App Dynamically


If you want to install a custom app dynamically from your app, then it is quite simple. For this, you need to place APK on a downloadable URL, so that it can be downloaded directly. Then you can access app url and install. Since you want to install app from your app, then you need to download the APK first and then install your custom app. It thus need to do in background. 
Here is the code.

I installed custom app on launch of my app i.e. MainActivity

//Download APK and then Install Custom App
InstallApp customApp= new InstallApp();
customApp.setContext(myContext);
customApp.execute("http://APK-URL/AppName.apk");

Following is the code to download the apk in background then install app.

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class InstallApp extends AsyncTask<String,Void,Void> {

    private Context context;
    private final String TAG = "InstallApp";
    public void setContext(Context context){

        this.context = context;
    }

    @Override
    protected Void doInBackground(String... apk_url) {

        try {

            //URL of the APK, to download
            URL download_url = new URL(apk_url[0]);
            HttpURLConnection c = (HttpURLConnection) download_url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            //Download APK to download folder. Save APK file with CustomApp.apk
            File file = new File(Environment.getExternalStorageDirectory() + "/download/");
            file.mkdirs();
            File downloadFile= new File(file, "CustomApp.apk");
            if(downloadFile.exists()){

                downloadFile.delete();
            }

            FileOutputStream fos = new FileOutputStream(downloadFile);
            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int lenght = 0;
            while ((lenght = is.read(buffer)) != -1) {

                fos.write(buffer, 0, lenght);
            }

            fos.close();
            is.close();

            //Install App Intent
            Intent install_intent = new Intent(Intent.ACTION_VIEW);
            install_intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "CustomApp.apk")), "application/vnd.android.package-archive");
            install_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(install_intent);
        } catch (Exception e) {

            Log.e(TAG, e.getMessage());
        }
        return null;
    }
}

Similarly, if you want to uninstall app from another app, then here is code:

 //Uninstall app
Uri packageUri = Uri.parse("package:"+"name of app  package");
//OS >= 14 supports ACTION_UNINSTALL_PACKAGE
//OS < 14 ACTION_DELETE
//Therefore, for all OS, use the following.

Intent appUninstall= new Intent( (Build.VERSION.SDK_INT >= 14)?Intent.ACTION_UNINSTALL_PACKAGE: Intent.ACTION_DELETE, packageUri);

startActivity(appUninstall);


Thursday, 10 November 2016

Device Information in Android

If you are working with any app that needs android device information, then don't worry. Getting device information is quite easy. Although there are several solutions available, but may be in pieces. I am developing a Mobile Device Management (MDM) app for which I've to gather device information. So, I decided to put everything at one place which may be useful for my fellow developers. Here is implementation of explicit information about any Android Device i.e. Phone, Tablet, Phone / Tablet with or without SIM.

private String sim_serial = "", sim_carrier = "", sim_country = "", device_manufacturer = "", device_model = "";
private String device_imei = "", device_serial = "", device_manufacturer_serial = "", device_OS_version = "";


//Get Device Info
 private void getDeviceInformation(){

        try{

            TelephonyManager tm =(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            boolean isSim = checkSIMCard();
            if(isSim){

                sim_serial =tm.getSimSerialNumber();
                sim_carrier=tm.getNetworkOperatorName();
                sim_country = tm.getSimCountryIso();
            }
            device_model = Build.MODEL;
            device_serial = Build.SERIAL;
            device_imei =tm.getDeviceId();
            device_manufacturer_serial = getManufacturerSerial();
            device_manufacturer = Build.MANUFACTURER;
            device_OS_version = android.os.Build.VERSION.RELEASE;
        }
        catch (Exception e){

            e.printStackTrace();
        }
    }

    //To check availability of SIM Card
    private boolean checkSIMCard(){

        TelephonyManager tm= (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        int simState = tm.getSimState();
        boolean isSIM = false;

        switch (simState) {

            case TelephonyManager.SIM_STATE_ABSENT:
                isSIM = false;
                break;

            case TelephonyManager.SIM_STATE_READY:
                isSIM = true;
                break;
        }
        return isSIM;
    }

    //Get manufacturer serial number, need in case of a non GSM Tablet.
    private String getManufacturerSerial() {

        String serial = null;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class);
            serial = (String) get.invoke(c, "ril.serialnumber", "unknown");
        } catch (Exception e) {

            e.printStackTrace();
        }
        return serial;
    }

Thank you for visiting my blog.
Cheers!

Thursday, 13 October 2016

List of Installed Apps on Android Device

Here is an easy way to get a list of installed apps on Android phone / tablet. 


PackageManager packManager = null;
ArrayList<ApplicationInfo> installedAppsList = new ArrayList<>();
try {
    packManager = context.getPackageManager();
    if (packManager != null) {
        
        installedAppsList = packManager .getInstalledApplications(0);
    }
} catch (Exception ex) {
       
       ex.printStackTrace();
}


Cheers!

Saturday, 7 May 2016

Create Button with Rounded Corners

Rounded corners buttons are very common for most of the applications. For this, it is more useful if you define a resource file in drawable folder for rounded corners. Define a custome style for button in styles file. Textcolor and background of button depends on your choice. You simply need to replace textcolor and background as per your needs. If you need only one button with rounded corners then you don't need to define style. Otherwise, for multiple buttons style will be very useful.

1. Create a resource rounded_corners.xml layout for rounded corners in @drawable.

This is rounded_corners_button.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:padding="10dp"
        android:shape="rectangle" >

        <!-- This is background color-->
        <solid android:color="#ffffff"/>
        <corners android:radius="5dp"/>
    </shape>
</resources>

2. Now, in styles file, define a custom style for a button with rounded corners. This style can be used for multiple Buttons of your application. Here is style for the button.

<style name="CutomButton" parent="android:style/Widget.Button" >
   <item name="android:layout_width">wrap_content</item>
   <item name="android:layout_height">wrap_content</item>
   <item name="android:textColor">#34bdab</item></item>  
   <item name="android:textSize">20sp</item></item>                   <item name="android:background">@drawable/rounded_corners_button</item>    
 </style>

3. Finally, in your activity layout, create a button and use above mentioned style for button as below:

<Button
             android:id="@+id/btn_signup"
             style="@style/CustomButton"
             android:text="@string/signup"
             android:layout_gravity="center_horizontal"/>

That's all you need for a rounded corner button.

RCPlease don't hesitate to contact me.
Thank you



RadioGroup - Radio Buttons with Selectors

In this post, I created a layout with three Radio buttons. Since all three radio buttons are distinct, therefore, one selector for each radio button. Selector is used to switch between Checked and Un-Checked states and load different images when radio button is checked and un-checked.

First things first, we create three selectors.

Selector One for First Radio Button:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
          <item android:drawable="@drawable/one_selected" android:state_checked="true"/>
          <item android:drawable="@drawable/one_unselected" android:state_checked="false"/>
</selector>

Selector Two for Second Radio Button:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
          <item android:drawable="@drawable/two_selected" android:state_checked="true"/>
          <item android:drawable="@drawable/two_unselected" android:state_checked="false"/>
</selector>

Selector Three for Third Radio Button:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
          <item android:drawable="@drawable/three_selected" android:state_checked="true"/>
          <item android:drawable="@drawable/three_unselected" android:state_checked="false"/>
</selector>

*one_selected / one_unselected etc. are two images which are shown when button is checked OR unchecked accordingly. Similarly, images required for other two radio buttons.

Now, create a layout and use aforementioned three selectors in respective radio buttons as below:

<?xml version="1.0" encoding="UTF-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
                 android:padding="5dp"
                 android:gravity="center"
                 android:layout_height="wrap_content"
                 android:layout_width="wrap_content"
                 android:layout_gravity="center_horizontal"
                 android:orientation="horizontal">

<RadioButton
                 android:layout_height="wrap_content"
                 android:layout_width="wrap_content" "
                 android:button="@null"
                 android:background="@drawable/selector_one"
                 android:layout_margin="5dp"
                 android:id="@+id/one"/>

<RadioButton
                 android:layout_height="wrap_content"
                 android:layout_width="wrap_content"
                 android:button="@null"
                 android:background="@drawable/selector_two"
                 android:layout_margin="5dp"
                 android:id="@+id/two"/>

<RadioButton
                 android:layout_height="wrap_content"
                 android:layout_width="wrap_content"
                 android:button="@null"
                 android:background="@drawable/selector_three"
                 android:layout_margin="5dp"
                 android:id="@+id/three"/>
</RadioGroup>

That's it.

Please don't hesitate to contact me.
Thank you