Reading text file from SD card - android

I have an app that send SMS for checking remaining MB in my data package. I have a layout with a button and a text view. When I press my button, I send a message to my phone operator. Then I have a broadcast receiver, that listens to incoming messages, and saves message body to a text file. I Want to show this text in my text view when I get answer from my operator.
This is my code:
public class bonbon3 extends Activity
{
Button btnStanje;
Context context=this;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
btnStanje = (Button) findViewById(R.id.provjeriStanje);
btnStanje.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String phoneNo = "0977";
String message = "stanje";
sendSMS(phoneNo, message);
Toast.makeText(getBaseContext(), "Zahtjev za provjeru stanja paketa je poslan, odgovor očekuj uskoro!", Toast.LENGTH_SHORT).show();
File root = Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/Bonbon info");
dir.mkdirs();
File f = new File(dir, "test.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
TextView tv = (TextView)findViewById(R.id.textView2);
tv.setText(text);
}
});
}
private void sendSMS(String phoneNumber, String message)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
}
Now, this code I am trying to read from file, before answer SMS is received, so I know this is wrong, but I don't know how to load text to textView after I get SMS answer?

hi i think this link will be very helpful for you
Reading a text file from sdcard in android is as same as reading a text file in java..

Goran, I cannot reply inline, but if you follow my link, there is pretty much everything you need.
I followed this example almost excatly and it worked out well.
You just need to implement a message handler in your activity (instead of the service as in the example) and push the message from the service (instead of recieving it here) but except that, this is exactely the same.
So in your activity, you should have something like this :
/**
* Handler of incoming messages from clients.
*/
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_GOT_SMS:
// Fill your text view here using the msg.obj (you put it there)
break;
default:
super.handleMessage(msg);
}
}
}
In you service (the bit that recieves the SMS) you should have something like:
public void sendText(String sms) {
// Create and send a message to the service, using a supported 'what' value
Message msg = Message.obtain(null, MyActivity.MSG_GOT_SMS,O, 0, sms);
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}

I think you would rather establish a messaging communication between your activity and your broadcast reciever (that is a service isn't it?).
You are bound to have a loop that will try to read the file continously until it is there whci does not feel right.
Do not store the SMS in a text file send the content directly from the activity to the service using the messaging system.
For messaging between activities and services, have a look in the Android developper guide about Bound services and especially the section about messenger (your service does not need to be bound).

Related

Linphone core listener not receiving incoming calls

I was trying to add sip incoming calls with linphone sdk, The registration is successful and I can make out going calls and the call status is logging as expected, but I am not able to receive incoming calls. I am using intent service to handle connection.
Here is my code:
protected void onHandleIntent(Intent intent) {
String sipAddress = intent.getStringExtra("address");
String password = intent.getStringExtra("password");
final LinphoneCoreFactory lcFactory = LinphoneCoreFactory.instance();
// First instantiate the core Linphone object given only a listener.
// The listener will react to events in Linphone core.
try {
lc = lcFactory.createLinphoneCore(new LinphoneCoreListenerBase() {
#Override
public void callState(LinphoneCore lc, LinphoneCall call, LinphoneCall.State state, String message) {
super.callState(lc, call, state, message);
Log.i(TAG, "callState: ");
}
}, getApplication());
} catch (LinphoneCoreException e) {
e.printStackTrace();
}
lc.setUserAgent("Test app", "1.0");
try {
LinphoneAddress address = lcFactory.createLinphoneAddress(sipAddress);
String username = address.getUserName();
String domain = address.getDomain();
if (password != null) {
lc.addAuthInfo(lcFactory.createAuthInfo(username, password, null, domain));
}
// create proxy config
LinphoneProxyConfig proxyCfg = lc.createProxyConfig(sipAddress, domain, null, true);
proxyCfg.setExpires(2000);
lc.addProxyConfig(proxyCfg); // add it to linphone
lc.setDefaultProxyConfig(proxyCfg);
running = true;
while (running) {
lc.iterate(); // first iterate initiates registration
sleep(20);
}
} catch (LinphoneCoreException e) {
e.printStackTrace();
}
}
What is wrong with my code?
As the IntentService document (https://developer.android.com/reference/android/app/IntentService) stated:
the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
I think you should not put the listener in an IntentService. Instead, put it in a long running Service so that the listener can actually keep staying there to receive events.

I am trying to sent mms (Multimedia Message Service). But it is not converting sms to mms. Only sending sms but not the image along with it

What am I trying to do:
I am sending an image(bitmap) and text from online server to direct in MMS. Whenever I will open my application all images(bitmap) and text will be automatically sent through default messaging application to all already inserted numbers in the server.
My Issue:
I am facing issue related to MMS. Sms is working fine. But when I sent MMS it only sent the text which is along with MMS, not the image(bitmap) nither converting the message into MMS.
Here is my MMS Class Code:
public class MainActivity extends AppCompatActivity {
Bitmap bitmap;
String[] a=new String[]{"name"};
private Settings settings=new Settings();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendMessage();
}
public void sendMessage() {
new Thread(new Runnable() {
#Override
public void run() {
com.klinker.android.send_message.Settings sendSettings = new com.klinker.android.send_message.Settings();
sendSettings.setMmsc(settings.getMmsc());
sendSettings.setProxy(settings.getPort());
sendSettings.setPort(settings.getProxy());
sendSettings.setUseSystemSending(true);
Transaction transaction = new Transaction(MainActivity.this, sendSettings);
bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_alert);
Message message = new Message("this is the text message sent with MMS", "0********",bitmap,"test");
// message.setImage());
transaction.sendNewMessage(message, Transaction.NO_THREAD_ID);
}
}).start();
}
}

Android Service does not update UI after running

I have an interesting issue that I have been trying to fix for over a week. Its on Android and involves a service running in the background to send a message on an app.
It is quite complex so I'll list the stages below:
1 - User enters message
2 - User selects 'send' button which launches the apps main service (ComService/START_STICKY) and activity (HomeScreen) hides the EditText box used for the message, replacing it with a TextView with the words 'Sending'
3 - Service spawns worker thread
4 - Service gets entered text off of activity and connects to server
5 - Service sends the message and then gets result from server
6 - Service disconnects from server
7 - Service updates activity to show sent message and shows the edit text
box again, as well as hides the TextView with the 'Sending' word
The issue is with stage 7. It uses a handler and message to communicate with the activity, as well as a separate class which holds the state of all of the activities in the app (to check if the UI is ok to update), but I commented this out from the code and the issue still exists so it is not this. The current set up works completely fine when the debugger is attached without any issues (why there is no logcat) and on the odd occasion when closing the app down and starting it up again. The problem begins when the debugger is detached and the app closed (via recent apps) for over around 5 seconds. The service completed its job by sending the message, as the message is added to the database and the user on the other end gets it, it is only the updating of the UI that is a problem, everything else seems to work fine!
Before sending the message, the service also connects to the server if there are any unread messages to indicate to other users that the user just read it. It follows very similar steps as above but was commented out and the issue still stays the same.
Ill post the code for the relevant steps below:
Stage 2
// Starts service to communicate with the server to send a message
Intent service = new Intent(this, ComService.class);
service.putExtra(ComService.requestType, ComService.sendTextMessage);
startService(service);
Stage 3
// Run when the service is being created
#Override
public int onStartCommand(Intent newIntent, int flags, int startId)
{
intent = newIntent;
currentInstance = this;
// Launches processing thread
ServiceHelper serviceHelper = new ServiceHelper(newIntent, this);
serviceHelper.start();
return Service.START_STICKY;
}
Stage 4/5/6/7
// Sends a message with only text content
public void startText()
{
// Initialises the class holding activity data
StateManager sm = new StateManager(context);
// Gets the data ready to be sent
if(sm.getHomeScreen())
{
// Friend id and time
friendId = HomeScreen.getFriendId();
// Gets the message text
messageTextContent = HomeScreen.getTextMessage(); // STAGE 4
}
else
{
allGood = false;
}
try
{
// Checks if any errors
if(allGood)
{
// Checks if message to be sent is blank
if(!messageTextContent.equals("") & messageTextContent.equals(" ") & !(messageTextContent == "") & !(messageTextContent == " "))
{
// Connects
(sh.new Utility()).connect(); // STAGE 4
// Checks if logged in
if((sh.new CheckLogin()).start())
{
// Sends request
sh.getNetwork().sendData(ServiceHelper.sendMessageTextRequest);
// Sends the friend id who message is addressed to
sh.getNetwork().sendData(friendId);
// Gets message date
messageDate = sh.getNetwork().getDataAsString();
// Sends the message type
sh.getNetwork().sendData(textType);
// Sends the message text
sh.getNetwork().sendData(messageTextContent); // STAGE 5
// Gets the message number
messageNumber = Integer.parseInt(sh.getNetwork().getDataAsString());
// Gets result and check if successful
String result = sh.getNetwork().getDataAsString(); // STAGE 5
if(!result.equals(ServiceHelper.requestSuccessful))
{
// Not successful
allGood = false;
errorMessage = result;
}
else
{
// Successful and saves data to database
addDatabaseTextMessage();
}
// Sends received indicator
sh.getNetwork().sendData(ServiceHelper.receivedIndicator);
}
else
{
allGood = false;
errorMessage = tryAgainMsg;
}
// Closes connection
(sh.new Utility()).finishConnection(); // STAGE 6
// Gets current friend record
UserDatabase db = new UserDatabase(context);
FriendRecord fr = db.getFriendRecord(Integer.parseInt(friendId));
// Increments message numbers by one and updates database
fr.setTotalExchanged(fr.getTotalExchanged() + 1);
db.updateFriendRecord(fr);
}
else
{
allGood = false;
errorMessage = msgBlank;
}
}
else
{
allGood = false;
errorMessage = tryAgainMsg;
}
} catch(IOException e)
{
allGood = false;
errorMessage = checkConnectionMsg;
// Adds to log cat
Log.e(this.getClass().getSimpleName(), e.getMessage());
} catch(Exception e2)
{
allGood = false;
errorMessage = tryAgainMsg;
// Adds to log cat
Log.e(this.getClass().getSimpleName(), e2.getMessage());
}
// Decides on result
if(allGood)
{
// Refreshes the ui
if(sm.getHomeScreen()) // STAGE 6
{
Message msg = HomeScreen.homeScreenInterface.obtainMessage(HomeScreen.sendSuccess); // STAGE 7
HomeScreen.homeScreenInterface.sendMessage(msg); // STAGE 7
}
}
else
{
// Indicates error on ui
if(sm.getHomeScreen())
{
Message msg = HomeScreen.homeScreenInterface.obtainMessage(HomeScreen.messageSendError); // STAGE 7
msg.obj = errorMessage; // STAGE 6
HomeScreen.homeScreenInterface.sendMessage(msg); // STAGE 7
}
}
}
State 7 (updating UI)
// Deals with service responses
public static Handler homeScreenInterface = new Handler()
{
#Override
public void handleMessage(Message msg)
{
switch(msg.what)
{
...
...
case HomeScreen.sendSuccess:
// Enables and clears input
HomeScreen.messageInput.setEnabled(true);
HomeScreen.messageInput.setText("");
// Shows the message send menu and hides sending text
HomeScreen.sendMenu.setVisibility(View.VISIBLE);
HomeScreen.sendingText.setVisibility(View.GONE);
// Clears message variable
message = "";
attachment = null;
try
{
// Reloads the message list
messageFriendId = "";
currentInstance.loadMessageList(true);
} catch (Exception e)
{
currentInstance.loadingScreen.open("Error", "Try again later!", true, "Ok", currentInstance);
}
// Checks if the message is sending
isMessageSending = false;
break;
...
...
}
}
};
Try using Broadcast Receiver instead of a handler to refresh your ui.
http://developer.android.com/reference/android/content/BroadcastReceiver.html
private BroadcastReceiver bReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("UPDATE")) {
String text = intent.getStringExtra("output");
updateUI(text);
}
else if(intent.getAction().equals("RESTART")) {
//other stuff
Board.this.startService(i);
}
}
};
//from Service
Intent intent = new Intent();
intent.setAction("UPDATE");
intent.putExtra("output",modifiedSentence);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
//onStart
LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
IntentFilter filter = new IntentFilter();
filter.addAction("UPDATE");
filter.addAction("RESTART");
bManager.registerReceiver(bReceiver, filter);
//onPause
LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
bManager.unregisterReceiver(bReceiver);

Trying to get an Android jabber app to check for a string in new messages and return a toast message

I have been able to create the if statement that checks for the string and it returns the toast message that i created but it keeps showing the toast message every time i open the chat. even if the most recent message doesn't contain the string I am looking for so i am assume it isn't checking to see if it is the last message received and it doesn't check to see if it is unread. the code is below. the reason i am trying to do this is because my parents share a facebook account and i want an easy way to display if the message is signed mom or dad. the code below only has the check for mom once it works i will be adding the check for dad signature. I am using the open source message client Xabber. Thank you for help.
public void setVisibleChat(String account, String user) {
final boolean remove = !AccountManager.getInstance()
.getArchiveMode(account).saveLocally();
AbstractChat chat = getChat(account, user);
if (chat == null)
chat = createChat(account, user);
else {
// Mark messages as read and them delete from db if necessary.
final ArrayList<MessageItem> messageItems = new ArrayList<MessageItem>();
for (MessageItem messageItem : chat.getMessages()) {
if (!messageItem.isRead()) {
messageItem.markAsRead();
messageItems.add(messageItem);
}
if (chat.getLastText().contains("Mom") && (!messageItem.isRead()));{
Toast.makeText(Application.getInstance(), "Message from Mom!", Toast.LENGTH_SHORT).show();
}
}
Application.getInstance().runInBackground(new Runnable() {
#Override
public void run() {
Collection<Long> ids = getMessageIds(messageItems, remove);
if (remove)
MessageTable.getInstance().removeMessages(ids);
else
MessageTable.getInstance().markAsRead(ids);
}
});
}
visibleChat = chat;
}
You've got an extra semi-colon here
if (chat.getLastText().contains("Mom") && (!messageItem.isRead())); <------
So your next block of code containing the Toast show statement will always be executed.
Remove the semi-colon

How to check in android how a program crashed?

Is there a tooling or maybe a log, where I can see what caused my application running on a android mobile phone, to hung or eventually crash?
I have programmed a signed application that is a runnable, it checks for messages on my server and send sms messages to a receiver, and after two or maybe 3 days, the application hungs or crashes.
How can I see what caused the crash?
Regards.
Shafqat
private void startservice() {
r = new Runnable()
{
public void run()
{
//execute the sms class and get the url
//build the url
SendSMS sms = null;
//TODO get the url from a database
Map<String, String> jsonitems = new JSONParser().parse(urlsmsservice+getDeviceId());
if(!jsonitems.isEmpty()){
sms = new SendSMS(context, jsonitems.get("PHONENUMBER").toString(), jsonitems.get("MESSAGE").toString());
sentReceiver.setCallbackUrl(jsonitems.get("CALLBACKURL").toString());
deliveredReceiver.setCallbackUrl(jsonitems.get("CALLBACKURL").toString());
sms.send();
}else{
Log.d(TAG, "No messages in Queue");
}
//handler.postDelayed(this, getInterval());
}
};
handler = new Handler();
thread = new Thread()
{
#Override
public void run() {
try {
while(thbool) {
sleep(getInterval());
handler.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
Make sure ADB tools are installed (they will be with the SDK). Then run adb logcat, which will show the system log output (useful is an exception is thrown). There are also free market applications which will show you the logcat buffer (aLogCat comes to mind).

Categories

Resources