Skip to content

Instantly share code, notes, and snippets.

@ajoydas
Created November 20, 2017 19:05
Show Gist options
  • Save ajoydas/a454f6093fff86b08336c297329ae2ee to your computer and use it in GitHub Desktop.
Save ajoydas/a454f6093fff86b08336c297329ae2ee to your computer and use it in GitHub Desktop.
SMS dualsim
package com.buet.dualsim.dualsim.activities;
import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.buet.dualsim.dualsim.R;
import com.buet.dualsim.dualsim.database.FNFHelper;
import com.buet.dualsim.dualsim.database.LogHelper;
import com.buet.dualsim.dualsim.database.PackageHelper;
import com.buet.dualsim.dualsim.database.SmsHelper;
import com.buet.dualsim.dualsim.database.UserInfoHelper;
import com.buet.dualsim.dualsim.utility.L;
import com.google.firebase.analytics.FirebaseAnalytics;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import static android.Manifest.permission.SEND_SMS;
import static com.buet.dualsim.dualsim.utility.SimUtil.selectedCallSim;
import static com.buet.dualsim.dualsim.utility.SimUtil.selectedSmsSim;
public class MessageActivity extends AppCompatActivity {
static final int PICK_CONTACT=1;
private static final int REQUEST_SMS = 0;
private static final int REQ_PICK_CONTACT = 2 ;
private EditText phoneEditText;
private EditText messageEditText;
private Button sendButton;
private ImageView pickContact;
private TextView sendStatusTextView;
private TextView deliveryStatusTextView;
FNFHelper fnfHelper;
SmsHelper smsHelper;
UserInfoHelper userInfoHelper;
LogHelper logHelper;
private BroadcastReceiver sentStatusReceiver, deliveredStatusReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
fnfHelper = new FNFHelper(this);
smsHelper = new SmsHelper(this);
userInfoHelper = new UserInfoHelper(this);
logHelper = new LogHelper(this);
phoneEditText = (EditText) findViewById(R.id.phone_number_edit_text);
messageEditText = (EditText) findViewById(R.id.message_edit_text);
sendButton = (Button) findViewById(R.id.send_button);
sendStatusTextView = (TextView) findViewById(R.id.message_status_text_view);
deliveryStatusTextView = (TextView) findViewById(R.id.delivery_status_text_view);
pickContact = (ImageView) findViewById(R.id.add_contact_image_view);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
L.m("Send button clicked");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
int hasSMSPermission = checkSelfPermission(SEND_SMS);
if (hasSMSPermission != PackageManager.PERMISSION_GRANTED) {
if (!shouldShowRequestPermissionRationale(SEND_SMS)) {
showMessageOKCancel("You need to allow access to Send SMS",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[] {SEND_SMS},
REQUEST_SMS);
}
}
});
return;
}
requestPermissions(new String[] {SEND_SMS},
REQUEST_SMS);
return;
}
sendMySMS();
}
else{
sendMySMS();
}
}
});
pickContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
// startActivityForResult(intent, 2);
}
});
}
/*public void sendMySMS() {
String phone = phoneEditText.getText().toString();
String message = messageEditText.getText().toString();
//Check if the phoneNumber is empty
if (phone.isEmpty()) {
Toast.makeText(getApplicationContext(), "Please Enter a Valid Phone Number", Toast.LENGTH_SHORT).show();
} else {
SmsManager sms = SmsManager.getDefault();
// if message length is too long messages are divided
List<String> messages = sms.divideMessage(message);
for (String msg : messages) {
PendingIntent sentIntent = PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT"), 0);
PendingIntent deliveredIntent = PendingIntent.getBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0);
sms.sendTextMessage(phone, null, msg, sentIntent, deliveredIntent);
}
}
}*/
public void sendMySMS() {
String phone = phoneEditText.getText().toString();
String message = messageEditText.getText().toString();
String name="";
//Check if the phoneNumber is empty
if (phone.isEmpty()) {
L.t(this, "Please Enter a Valid Phone Number");
} else {
L.m("Calculating sms cost.......");
int simID = selectedSmsSim(phone,fnfHelper,userInfoHelper,smsHelper,logHelper);
L.m("Selected sim:"+simID);
if (simID < 0) {
L.t(this, "Please select sim and package details.");
return;
}
simID--;
if (simID == 0) {
name = "isms";
} else if (simID == 1) {
name = "isms2";
}
boolean result;
PendingIntent sentIntent = PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT"), 0);
PendingIntent deliveredIntent = PendingIntent.getBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0);
ArrayList<String> messageList = SmsManager.getDefault().divideMessage(message);
if (messageList.size() > 1) {
result = sendMultipartTextSMS(name,this, simID, phone, null, messageList, null, null);
} else {
result = sendSMS(name, this, simID, phone, null, message, null, null);
}
if(result==false)
{
if (simID == 0) {
name = "isms0";
} else if (simID == 1) {
name = "isms1";
}
if (messageList.size() > 1) {
result = sendMultipartTextSMS(name,this, simID, phone, null, messageList, null, null);
} else {
result = sendSMS(name, this, simID, phone, null, message, null, null);
}
}
if(result == false){
L.t(this,"Sorry. Message switching on your device isn't supported by us yet.");
}
}
}
public static boolean sendSMS(String name, Context ctx, int simID, String toNum, String centerNum, String smsText, PendingIntent sentIntent, PendingIntent deliveryIntent) {
try{
Method method = Class.forName("android.os.ServiceManager").getDeclaredMethod("getService", String.class);
method.setAccessible(true);
Object param = method.invoke(null, name);
method = Class.forName("com.android.internal.telephony.ISms$Stub").getDeclaredMethod("asInterface", IBinder.class);
method.setAccessible(true);
Object stubObj = method.invoke(null, param);
if (Build.VERSION.SDK_INT < 18) {
method = stubObj.getClass().getMethod("sendText", String.class, String.class, String.class, PendingIntent.class, PendingIntent.class);
method.invoke(stubObj, toNum, centerNum, smsText, sentIntent, deliveryIntent);
} else {
method = stubObj.getClass().getMethod("sendText", String.class, String.class, String.class, String.class, PendingIntent.class, PendingIntent.class);
method.invoke(stubObj, ctx.getPackageName(), toNum, centerNum, smsText, sentIntent, deliveryIntent);
}
return true;
} catch (ClassNotFoundException e) {
L.e("ClassNotFoundException:" + e.getMessage());
} catch (NoSuchMethodException e) {
L.e("NoSuchMethodException:" + e.getMessage());
} catch (InvocationTargetException e) {
L.e("InvocationTargetException:" + e.getMessage());
} catch (IllegalAccessException e) {
L.e("IllegalAccessException:" + e.getMessage());
} catch (Exception e) {
L.e("Exception:" + e.getMessage());
}
return false;
}
public static boolean sendMultipartTextSMS(String name,Context ctx, int simID, String toNum, String centerNum, ArrayList<String> smsTextlist, ArrayList<PendingIntent> sentIntentList, ArrayList<PendingIntent> deliveryIntentList) {
try {
Method method = Class.forName("android.os.ServiceManager").getDeclaredMethod("getService", String.class);
method.setAccessible(true);
Object param = method.invoke(null, name);
method = Class.forName("com.android.internal.telephony.ISms$Stub").getDeclaredMethod("asInterface", IBinder.class);
method.setAccessible(true);
Object stubObj = method.invoke(null, param);
if (Build.VERSION.SDK_INT < 18) {
method = stubObj.getClass().getMethod("sendMultipartText", String.class, String.class, List.class, List.class, List.class);
method.invoke(stubObj, toNum, centerNum, smsTextlist, sentIntentList, deliveryIntentList);
} else {
method = stubObj.getClass().getMethod("sendMultipartText", String.class, String.class, String.class, List.class, List.class, List.class);
method.invoke(stubObj, ctx.getPackageName(), toNum, centerNum, smsTextlist, sentIntentList, deliveryIntentList);
}
return true;
} catch (ClassNotFoundException e) {
L.e("ClassNotFoundException:" + e.getMessage());
} catch (NoSuchMethodException e) {
L.e("NoSuchMethodException:" + e.getMessage());
} catch (InvocationTargetException e) {
L.e("InvocationTargetException:" + e.getMessage());
} catch (IllegalAccessException e) {
L.e("IllegalAccessException:" + e.getMessage());
} catch (Exception e) {
L.e("Exception:" + e.getMessage());
}
return false;
}
public void onResume() {
super.onResume();
sentStatusReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
String s = "Unknown Error";
switch (getResultCode()) {
case Activity.RESULT_OK:
s = "Message Sent Successfully !!";
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
s = "Generic Failure Error";
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
s = "Error : No Service Available";
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
s = "Error : Null PDU";
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
s = "Error : Radio is off";
break;
default:
break;
}
sendStatusTextView.setText(s);
}
};
deliveredStatusReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
String s = "Message Not Delivered";
switch(getResultCode()) {
case Activity.RESULT_OK:
s = "Message Delivered Successfully";
break;
case Activity.RESULT_CANCELED:
break;
}
deliveryStatusTextView.setText(s);
phoneEditText.setText("");
messageEditText.setText("");
}
};
registerReceiver(sentStatusReceiver, new IntentFilter("SMS_SENT"));
registerReceiver(deliveredStatusReceiver, new IntentFilter("SMS_DELIVERED"));
}
public void onPause() {
super.onPause();
try {
unregisterReceiver(sentStatusReceiver);
unregisterReceiver(deliveredStatusReceiver);
}catch (IllegalArgumentException e){}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sim, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.homeButton) {
try {
unregisterReceiver(sentStatusReceiver);
unregisterReceiver(deliveredStatusReceiver);
}catch (IllegalArgumentException e){}
Intent intent=new Intent(MessageActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
return super.onOptionsItemSelected(item);
}
private boolean checkPermission() {
return ( ContextCompat.checkSelfPermission(getApplicationContext(), SEND_SMS ) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{SEND_SMS}, REQUEST_SMS);
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_SMS:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
L.t(getApplicationContext(), "Permission Granted, Now you can access sms");
sendMySMS();
}else {
L.t(getApplicationContext(), "Permission Denied, You cannot access and sms");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(SEND_SMS)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{SEND_SMS},
REQUEST_SMS);
}
}
});
return;
}
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(MessageActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
/* @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_PICK_CONTACT) {
if (resultCode == RESULT_OK) {
Uri contactData = data.getData();
Cursor cursor = managedQuery(contactData, null, null, null, null);
cursor.moveToFirst();
String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneEditText.setText(number);
}
}
}*/
@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id =c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone =c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,
null, null);
phones.moveToFirst();
String cNumber = phones.getString(phones.getColumnIndex("data1"));
L.m("number is:"+cNumber);
phoneEditText.setText(cNumber);
}
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment