Can't send a SMS using SmsManager in android - android

I want to send a sms from my android phone but it doesn't work.
here is my code:
public class MainActivity extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendMessage(View view){
String msg,number;
number= "***********";
msg="This is a message";
try{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, msg,null,null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
}catch(Exception ex){
Toast.makeText(getApplicationContext(),"SMS failed, please try again.",Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
I include 'uses-permission android:name="android.permission.SEND_SMS"'
I run this code from my android phone but it doesn't send any message.
If there is any error how can i see those error and how to fix it.
Please Help me.Thanks in advance.

use this website for reference
<uses-permission android:name="android.permission.SEND_SMS" />

According to your code, the problem is that you haven't called the sendMessage method.
You need to have an action that occurs when you click a button. Google how that is done on Android. Once you have that worked out, you should be able to make the button click to call the sendMessage method.
Also, you'll need to know how to view the error log. There are a number of apps that allow you to do this. It is important to know how to view the error log so that way if your Toast finally pops up, you'll be able to check the log to see why this happened.

I guess you have the sendMessage() some where in the code if you trigger a button click? sendTextMessage work well. Anyway, make sure that you've validated if number is null or bad formatted. This may causes the problem. Make also sure that you are using the proper SMSMAnager (android.telephony.SmsManager) instead of android.telephony.gsm.SmsManager. SEND_SMS permission is also required.

I solve the problem.Actually the problem is for dual sim. And always i deactivate my first sim(Sim1). But this is the problem.My app always find my first sim message center number but i deactivate Sim1.Now i activate my first sim and this is worked.Thanks to all for your answer and help

Related

Why is the IncomingNumber always empty?

I'm totally new to mobile programming and to Xamarin or Xamarin.Forms. So I thought about starting small and trying a first app that is showing the phone number of an incoming call (just to know how to get this information into my app).
After a lot of trying and searching the net and not finding appropriate answers, I managed to at least be able to hit break points when there's an incoming call.
For that I created a class called StateListener in the Android specific project of my Xamarin.Forms solution. This class looks like that:
public class StateListener : PhoneStateListener
{
public override void OnCallStateChanged(CallState state, string incomingNumber)
{
base.OnCallStateChanged(state, incomingNumber);
switch (state)
{
case CallState.Ringing:
break; // <== set break point here
case CallState.Offhook:
break;
case CallState.Idle:
break;
}
}
}
And I instantiated this class in my MainActivity's OnCreate method like this:
StateListener phoneStateListener = new StateListener();
TelephonyManager telephonyManager = (TelephonyManager)GetSystemService(Context.TelephonyService);
telephonyManager.Listen(phoneStateListener, PhoneStateListenerFlags.CallState);
Now, when I run my little solution then the break point (see comment in code) is hit, but unfortunately the incomingNumber of the OnCallStateChanged method is always empty.
Following the unsatisfying documentation about the OnCallStateChanged method I set the needed Permission.ReadPhoneState permission in the manifest file, but that didn't help.
Maybe you can?
As doc says:
If application does not have READ_CALL_LOG permission or carrier
privileges (see TelephonyManager.hasCarrierPrivileges()), an empty
string will be passed as an argument.
so please check your application permissions.
It seems that once you emulated your app you have to set any new permissions manually inside the emulated Android, your app won't ask for it, since it's already installed.
After I gave my app the "Phone" permissions inside the emulated Android and restarted my app, I got the incomingNumber.

Creating a log trace of the application life cycle

I have created an application that extensively requires user inputs and interaction and even though I have made sure that I test and catch every possible case that might throw an error I want to be able to create a mechanism that traces the error in case my application crashes on the field.
I want to be able to record the entire flow right from a button click till whatever the user might be selecting or the navigation between the pages in a log file such that in case my application crashes I'm able to study the trace file later and know exactly where the error occurred.
I'm very new to this sort of programming and therefore any pointers on the above will be very helpful! Thank you in advance :]
PS: I'm not even sure whether what im referring to will be correctly called a "log trace" or not so any edit is welcome. :)
EDIT : I also want to be able to save the error report generated and send it to a particular id (similar to 'send an error report to xyz).
UPDATE :
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try {
File myFiles = new File("/sdcard/ScanApp");
if(!myFiles.exists())
{
myFiles.mkdirs();
}
File myFile = new File("sdcard/ScanApp/log.txt");
myFile.createNewFile();
myFile.delete();
myFile.createNewFile();
String cmd = "logcat -d -v time -f "+myFile.getAbsolutePath()+ " -s ActivityManager:V";
Runtime.getRuntime().exec(cmd);
Logs.this.finish();
}
catch (Exception e)
{
flag=1;
error=e.getMessage();
}
I used this in a previous application for recording any application activity and make a textfile and save it to the SD card, but the contents weren't exactly what I was looking for. Is the solution im looking for something along these lines?
Here, check for the link for reference.
In here you create a class say ExceptionHandler that implements java.lang.Thread.UncaughtExceptionHandler..
Inside this class you will do your life saving stuff like creating stacktrace and gettin ready to upload error report etc....
Now comes the important part i.e. How to catch that exception.
Though it is very simple. Copy following line of code in your each Activity just after the call of super method in your overriden onCreate method.
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));
Your Activity may look something like this…
public class ForceClose extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));
setContentView(R.layout.main);
}
}
Hope this helps...
You need to look up on Exception Handling. That is when your application crashes or any other app level errors occur, the code in the exception block executes. So in that place, log that error in a text-file and which solves your "log trace" issue.
Refer the link for beautiful examples.

Android - SMS Loopback

I wish to achieve a SMS loopback, i.e. to send and receive SMS from the same application. In order to do so, I have created a class that extends BroadcastReciever, implemented the onReceive() method, and declared the relevant permissions.
I verified the implementation by sending a SMS using telnet.
I want to automate the telnet process, i.e. having the application test itself by sending the SMS. In order to do so, I invoke the following method in the main activity, but the BroadcastReceiver is never called:
private final void sendSMS() {
final TelephonyManager telMgr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
final int len = telMgr.getLine1Number().length();
final String phoneNum = telMgr.getLine1Number().substring(len - 4, len);
final String msg = "msg";
SmsManager.getDefault().sendTextMessage(phoneNum, null, msg, null, null);
}
Any clue what is wrong...?
UPDATE: Note that the code above is intended for the emulator.
Not sure if I understand you question right, but are you trying send an SMS from the emulator to itself? As far as I know, that is not possible. Just load up another emulator, and send messages between them.
Since telnet commands work, your BroadcastReceiver is probably correctly implemented, but you should probably attach the code for it anyways... Its hard to troubleshoot code you can't see :)

Why does logcat ignore log statements with tag "PHONE"?

I was setting a listener on my call button and at first I just wanted to make sure that the listener was working, so I put a log statement inside of it. But for some mysterious reason, it refused to print when I clicked it! So maybe the call button was null, I thought, and added an else statement...but it didn't print anything from either the if or the else statement!!! It would print the statements before and after, but totally ignore everything in the if-else structure. Here's the code:
ImageButton call = (ImageButton) v.findViewById(R.id.callButton);
Log.d("MEETINGS", "ABOUT TO WORK W/ CALL");
Log.e("MEETINGS", "" + (call != null));
if (call != null) {
Log.d("PHONE", "setting stuff on call...");
call.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d("PHONE", "on call : " + phone);
}
});
} else {
System.out.println("why is this messed up");
Log.d("PHONE", "call button was null!");
}
System.out.println("what the heck is going on");
After at least 15 minutes of trying to unravel the mystery of how Java could just decide to skip both the if and the else, I tried giving the log statement a different tag.
And eureka! That did the trick! I changed "PHONE" to "BLAH" and suddenly the world made sense again! Curious, I changed it to "phone" and it refuses to print again.
Moral of the story: never use the tag "phone" or "PHONE" in logcat!!!
Can someone please explain to me how and/or why logcat ignores messages with the tag "PHONE"?
See the documentation for isLoggable(). I'm guessing debug output for the "PHONE" tag has been disabled on your phone to suppress output from the actual phone application.
I believe you should be able to run "getprop log.tag.PHONE" in a shell on the phone to retrieve the minimum severity level required for messages tagged "PHONE" to be printed.

Android App crashes in emulator - logs blank

I am completely new to android, and pretty much a Java newb.
I have a simple app that I am building to get the hang of android's development environment - and things like click events, etc..
The app loads, and I am able to change the text in a textfield using a button handler. However, when I import the location class, and try to do a simple GPS call, the application crashes.
The problem is, everything looks good in Eclipse (error console) - and I'm not seeing any exceptions in the android emulator (DevTools). I have the logcat window open, but I haven't done anything in eclipse/code to send logcat anything (do I need to?)
Can anyone see something wrong with this? Is there a better way to troubleshoot?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import android.location.*;
public class locationDisplay extends Activity {
private EditText text;
private Location GPSLocation;
double dblLat;
double dblong;
String strLat;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // bind the layout to the activity
text = (EditText) findViewById(R.id.EditText01);
text.setText("No button pressed");
}
// Handler for each button -- Button01 is when it crashes
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.Button01:
dblLat = GPSLocation.getLatitude();
strLat = Double.toString(dblLat);
text.setText(strLat);
break;
case R.id.Button02:
text.setText("Button 2 was clicked");
break;
case R.id.Button03:
text.setText("Button 3 was clicked");
break;
}
}
You shouldn't need to write anything to get the default messages in LogCat; uncaught exception reports should appear automatically when your program crashes. However, sometimes LogCat and your emulator get disconnected from each other and the messages simply all disappear. Simply close Eclipse and the emulator, restart them both, and the messages should reappear. An easy way to tell whether the link has been re-established is during the boot-up of the emulator. Just as the flashing "ANDROID" text in the fancy font disappears bringing you to the lockscreen, you should see about a hundred lines of text flash by on LogCat. If that doesn't happen, then LogCat isn't getting its messages.
The way to display debugging messages in Android is to use the Log.d("some name for your log statements so you can filter the LogCat messages", "The actual debug statement here");. You'll often find people using things like a static final String LOG_TAG in their application so that they can make sure their logs always have the same tag, and hence, the filter never misses a message.
As for your actual code here, Rpond is right, you never initialised your GPSLocation object.
You GPSLocation object is null. You need to access the LocationService to get a current location. And with the emulator you will need to manually send locations.
Location Services
Sometimes LogCat 'forgets' you have a device/emulator connected and running. It seems like this happens after you have a device and an emulator online at the same time and then you disconnect one of them. If you are getting nothing from LogCat, go to Window>Show View>Other>Devices and then click the device that you want to log.

Categories

Resources