How Do I send A Text Via SmsManager? - java

so I have a button that when clicked, I want to send a text message. To who, is specified by the editText. When I use the app, it says that the text is sent, however when I check in my messaging app it shows that nothing sent. How do I remedy this?
Example Number: "8667404531" (This is a bot hotline for example)
EditText editText = (EditText) findViewById(R.id.editText);
String myNum = editText.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(myNum, null, "Wake Up!", null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}

First, make sure you have set this permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.SEND_SMS"/>
Secondly, you should check self permission before you can send any messages. You can achieve that with checkSelfPermission() call and corresponding onRequestPermissionsResult() callback.
Check out this code below, it contains important parts related to requesting permissions from the device. This code below is a complete example of Activity for sending SMS from your device:
public class MainActivity extends AppCompatActivity {
EditText number, text;
Button send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number = (EditText) findViewById(R.id.editText);
text = (EditText) findViewById(R.id.editText2);
send = (Button) findViewById(R.id.button);
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.SEND_SMS)){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.SEND_SMS}, 1);
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.SEND_SMS}, 1);
}
} else {
//do nothing
}
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = number.getText().toString();
String messageText = text.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, messageText, null, null);
Toast.makeText(MainActivity.this, "Message sent!", Toast.LENGTH_SHORT).show();
} catch (Exception e){
Toast.makeText(MainActivity.this, "Sending failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case 1:{
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED){
Toast.makeText(MainActivity.this, "Permission granted!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Permission not granted!", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
}

Related

Why my button work juste one time ? - Android studio

I am trying tp send sms by clicking a button bt this button is working juste one time.
And i don't know how I can get it so the button can be pressed an infinite amount of time.
Can you please help me to fix that.
this is my code :
Button sendBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
protected void sendSMSMessage() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("+212xxxxxx", null, "Je suis en danger, voici ma localisation : https://goo.gl/maps/xamxKW62p34wWpBU8", null, null);
Toast.makeText(getApplicationContext(),
"SMS sent.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}
}
You are missing else branch in sendSMSMessage, so you are not sending SMS if SEND_SMS permission is already granted. You are also not doing anything if you need to show permission rationale, which results in a broken experience.
Overall I would suggest to read carefully the docs on requesting permissions. It explains both your approach with onRequestPermissionsResult as well as the new recommended way of using ActivityResultContracts.
Without rewriting your code to the contracts I would fix it like this:
protected void sendSMSMessage() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
// fixme: show explanation
// before requesting the permission again
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
} else {
sendSmsImpl();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
sendSmsImpl();
} else {
// fixme: explain that it can't send SMS without the permission
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
// !!! NOTE: you still need break inside switch/case
// even with curly braces
break;
}
}
}
private void sendSmsImpl() {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("+212xxxxxx", null, "Je suis en danger, voici ma localisation : https://goo.gl/maps/xamxKW62p34wWpBU8", null, null);
//todo: use sentIntent argument of sendTextMessage to detect success/error
Toast.makeText(getApplicationContext(),
"SMS sent.", Toast.LENGTH_LONG).show();
}

call by phone number on button click (java)

I have a call method on button click
button_call=(Button) findViewById(R.id.button_call);
button_call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+79142214017"));
startActivity(intent);
}
});
And the data transfer method in Firebase
private void validateClientInfo() {
if (TextUtils.isEmpty(client_edit.getText().toString())) {
Toast.makeText(this, "Введите имя", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(client_number.getText().toString())){
Toast.makeText(this, "Введите номер", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> userMap = new HashMap<>();
userMap.put("uid", mAuth.getCurrentUser().getUid());
userMap.put("numberphone_client",client_number.getText().toString());
clientRef.child(mAuth.getCurrentUser().getUid()).updateChildren(userMap);
startActivity(new Intent(ClientName.this,HomeActivity.class));
}
}
transcripts
client_number=(EditText) findViewById(R.id.client_number);
mAuth=FirebaseAuth.getInstance();
how to make it so that when the call button is pressed, the number is received and called?
I want that when the button _call button is pressed, the data transmitted by the transfer method is received and a call is made on them.
Request permission android.permission.CALL_PHONE before calling.
Add into AndroidManifest.xml:
<uses-permission android:name="android.permission.CALL_PHONE" />
Request permission before calling:
boolean isPermissionGranted = (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED);
if (isPermissionGranted) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + mNumber));
startActivity(intent);
} else {
Toast.makeText(this, "Отсутствует разрешение на звонок с устройства", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.CALL_PHONE }, 0);
}
Add request result:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull #NotNull String[] permissions, #NonNull #NotNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 0) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
//RETURN, PERMISSION NOT GRANTED
Toast.makeText(this, "Вы не выдали разрешение, приложение может работать неккоректно!", Toast.LENGTH_SHORT).show();
return;
}
}
//PERMISSIONS GRANTED
Toast.makeText(this, "Спасибо за выданное разрешение!", Toast.LENGTH_SHORT).show();
}
}
If your are looking to call the selected number then just use the following code.
Intent intentCallForward = new Intent(Intent.ACTION_DIAL); // ACTION_CALL
Uri uri2 = Uri.fromParts("tel", "79142214017, "#");
intentCallForward.setData(uri2);
startActivityForResult(intentCallForward, 101);

Increment float number on phone state idle

I am trying to increment a float number once the Phone State is IDLE. Then save the float number in shared preferences and expose it in the main activity.
Currently what i did was use intent to take in the number on phone state and send to the main activity and on the main activity i saved it. But the phone crashes once i test it. Below is my current code for the Incoming Call:
public class IncomingCall extends BroadcastReceiver {
private View view;
#Override
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
Intent intentBundle = new Intent();
Bundle bundle = new Bundle();
bundle.putFloat("value", 0.5f);
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
bundle.putFloat("value", 0.5f);
intentBundle.putExtras(bundle);
Toast toast = new Toast(context);
CharSequence text = "O.5 Added";
int duration = Toast.LENGTH_SHORT;
Toast testtoast = Toast.makeText(context, text, duration);
testtoast.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Below is the code i have in my main activity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private float minteger = 0.5f;
private Context context;
private Activity activity;
private static final int PERMISSION_REQUEST_CODE = 1;
private View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SharedPreferences sharedPreferences = this.getSharedPreferences("com.appname.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putFloat("value", minteger).apply();
Float value = sharedPreferences.getFloat("value", 0.0f);
TextView textv = (TextView) findViewById(R.id.numberValue);
textv.setText(String.valueOf(value));
context = getApplicationContext();
activity = this;
Button check_permission = (Button) findViewById(R.id.check_permission);
Button request_permission = (Button) findViewById(R.id.request_permission);
check_permission.setOnClickListener(this);
request_permission.setOnClickListener(this);
}
#Override
public void onClick(View v) {
view = v;
int id = v.getId();
switch (id) {
case R.id.check_permission:
if (checkPermission()) {
Snackbar.make(view, "Permission already granted.", Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(view, "Please request permission.", Snackbar.LENGTH_LONG).show();
}
break;
case R.id.request_permission:
if (!checkPermission()) {
requestPermission();
} else {
Snackbar.make(view, "Permission already granted.", Snackbar.LENGTH_LONG).show();
}
break;
}
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.READ_PHONE_STATE)) {
Toast.makeText(context, "Phone state allows you to earn on incoming calls. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Snackbar.make(view, "Permission Granted, Now you can access phone manager.", Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(view, "Permission Denied, You cannot access phone manager.", Snackbar.LENGTH_LONG).show();
}
break;
}
}
}
You could put the value to sharedpref in IncomingCall and retrieve in MainActivity.

send sms from SMSPortalFragment not working

I have been trying to send test messages from using send_sms api. My SMSPortalFragment.java code show no error. Also there is no other error shown in Logcat.
The code builds and installs in the Galaxy S8.
The app runs fun.
Going to fragment_smsportal.xml is working fine.
I can type in my name and message.
On button click it asks for my PERMISSION in runtime.
NO MESSAGE IS SENT EVEN AFTER I ALLOW PERMISSION.
java code:
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
Button sendButon;
EditText fullName;
EditText textMessage;
String phoneNo = "***********";
String name;
String message;
String sendMessage;
public SMSPortalFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View smsportal = inflater.inflate(R.layout.fragment_smsportal, container, false);
fullName = (EditText) smsportal.findViewById(R.id.fullName);
textMessage = (EditText) smsportal.findViewById(R.id.textMessage);
sendButon = (Button) smsportal.findViewById(R.id.sendButon);
sendButon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendSMSMessage();
}
});
return smsportal;
}
private void sendSMSMessage() {
name = fullName.getText().toString();
message = textMessage.getText().toString();
sendMessage = name + " " + message;
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sendMessage, null, null);
Toast.makeText(getActivity(),"SMS sent.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(),"SMS failed, please try again.", Toast.LENGTH_LONG).show();
}
}
}
}
Can anyone tell me what I am doing wrong?
PS: I removed my phone number from this code for security concern.
Do not write your send logic in onRequestPermissionsResult()
and
Try this...
Manifest permission
<uses-permission-sdk-23 android:name="android.permission.SEND_SMS"/>
and here is the snippet
try {
Bundle msgDataBundle = intent.getExtras();
String mobileNumber = msgDataBundle.getString("MobileNumber");
SmsManager smsManager = SmsManager.getDefault();
// smsManager.sendTextMessage(mobileNumber,null,"sam",null,null);
smsManager.sendTextMessage(mobileNumber, null, "Test Sample Message Text", null, null);
Toast.makeText(context, "SMS Sent!", Toast.LENGTH_LONG).show();
Log.d("---", "Sent");
} catch (Exception e) {
Toast.makeText(context, "SMS faild, please try again.", Toast.LENGTH_LONG).show();
Log.d("---", "Fail");
e.printStackTrace();
}

Android value to Sqlite table

Hi I am developing and android app in which a login and signup page is there when user enters the username and password a passcode will be sent to the mobile number and after that he will enter to registation page where he needs to enter username,password and passcode for verification.. So I need is a random value has to be given to the table like'1' or something for successful registration..else '0' like that.. can anyone help..
Register Activity
public class RegisterActivity extends Activity {
LoginDataBaseAdapter loginDataBaseAdapter;
Button btnReg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_xm);
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
btnReg = (Button) findViewById (R.id.buttonRegister);
final EditText editTextUserName=(EditText)findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)findViewById(R.id.editTextPasswordToLogin);
final EditText editTextMobileNumber = (EditText)findViewById(R.id.editText1);
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String mobileNumber = editTextMobileNumber.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
String sd = getIntent().getStringExtra("number");
String name = editTextUserName.getText().toString();
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword) && (mobileNumber.equals(sd)))
{
Toast.makeText(RegisterActivity.this, "Congrats: Registration Successfull", Toast.LENGTH_LONG).show();
Intent in = new Intent(RegisterActivity.this,HomePageActivity.class);
startActivity(in);
}
else
{
Toast.makeText(RegisterActivity.this, "User Name, Passcode or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
signup Activity
public class SignUpActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword, editMobileNumber;
Button btnCreateAccount;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
Random r = new Random();
int number =r.nextInt(9999 - 1000) + 1000;
LoginDataBaseAdapter loginDataBaseAdapter;
private static String url_create_data = "http://iascpl.com/app/create_data1.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_xm);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get References of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
editMobileNumber = (EditText)findViewById(R.id.mobileNumber);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
String phoneNo = editMobileNumber.getText().toString();
String sms = Integer.toString(number);
//Intent intent = new Intent(SignUpActivity.this, RegisterActivity.class);
//intent.putExtra("number", sms + "");
//startActivity(intent);
//new CreateNewProduct().execute();
StringTokenizer st=new StringTokenizer(phoneNo,",");
while (st.hasMoreElements())
{
String tempMobileNumber = (String)st.nextElement();
if(tempMobileNumber.length()>0 && sms.trim().length()>0)
{
sendSMS(tempMobileNumber, sms);
}
else
{
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
}
// check if any of the fields are vacant
if(name.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(name, password);
Toast.makeText(getApplicationContext(), "Passcode is sent to the mobile number you provided. ", Toast.LENGTH_LONG).show();
new CreateNewProduct().execute();
// Intent intent = new Intent(SignUpActivity.this, RegisterActivity.class);
// intent.putExtra("number", sms + "");
// startActivity(intent);
}
}
});
}
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
},new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignUpActivity.this);
pDialog.setMessage("Creating a new account..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
String mobile = editMobileNumber.getText().toString();
String sms = Integer.toString(number);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("mobile", mobile));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_data,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(SignUpActivity.this, RegisterActivity.class);
i.putExtra("number", sms + "");
startActivity(i);
//closing this screen
//finish();
} else {
// failed to create product
return "false";
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
/*protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}*/
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == "false")
Toast.makeText(SignUpActivity.this, "User Name already exists. Please choose another user name ", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}
}
You can generate different random values like this.
System.currentTimeMillis(); //It return long value of current time. This value always will be unique.

Categories

Resources