Continuously read buffer stops App - android

My App recieves a neverending datastream from a bluetooth device.
I am reading this stream in a while(true) loop and can see the read data in my log.
The problem is, that my device is not responding anymore. Is there a (hopefully) simple way to let the application read the stream in the background?
Thanks!
Christian.
#boulder:
Sorry, I don't really understand that AsynkTask class. :(
Can you please help me with this code putting it in the background?
Thank you very much!
try {
while (true)
{
read = isBT.read(msgBuffer);
connected = true;
StringBuilder strBuffer = new StringBuilder();
for (int i = 0; i<read; i++)
{
int b = msgBuffer[i];
strBuffer.append(b);
}
Log.d(TAG,"++++++ Read "+ read + " Bytes: " + strBuffer.toString());
}
}
catch (IOException e) {
Log.d(TAG," +++ IOException ++++", e);
}

May be this will be helpful http://android-developers.blogspot.com/2009/05/painless-threading.html
Handler example:
private static final String CONTENT_TAG = "content";
// Call this from datastream thread to post data
private void postProgress(String aBufferContent) {
// Wrapping data in bundle
final Bundle bundle = new Bundle();
bundle.putString(CONTENT_TAG, aBufferContent);
// Sending message to handler
final Message message = mProgressHandler.obtainMessage();
message.setData(bundle);
mProgressHandler.sendMessage(message);
}
// This will be executed in UI thread. Do you GUI update job here
private final Handler mProgressHandler = new Handler() {
public void handleMessage(Message msg) {
final String streamContent = msg.getData().getString(CONTENT_TAG);
myTextView.setText(streamContent);
}
};

Related

PJSUA2 Android - Incoming calls drop after 32 seconds

I'm building a PJSUA2 (PJSIP 2.8) Android app and I have some issues: i.e. only on incoming call, call state remains in "PJSIP_INV_STATE_CONNECTING" and after 32 seconds the call drops.
I'm looking for the cause of the issue since several days, I googled a lot and all what I found is: in most situations this issue is related to NAT management or network issues related to NAT. In a few words: in most cases the called party does not receive the ACK after answering the call.
Finally I was able to log all SIP messages between my app and the SIP server and found that my app receives the ACK from the server, so I suppose it's not a network related issue.
I compiled PJSIP 2.8 with OpenSSL and SRTP support, but without video support (I don't need it at least at the moment). If it makes any difference, the app has a target version 28 and minimum SDK version 19.
I tried several apps on the market and they work fine enough with and without SRTP and with all signaling transports (UDP, TCP, TLS), WebRTC works fine too (tested with SipML5), so I would exclude a server misconfiguration. My app does the same (except SRTP with which I have some issues at the moment).
I tried with a SIP provider too (MessageNet) using UDP and the behaviour is always the same. I tried to use compact SIP messages and it behaves the same, with and without uri parameters, with and without STUN and or ICE and nothing changes. Mobile network and WiFi networks give the same results.
I tried to debug inside PJSIP library too, but without any success, then I tried to follow the code, to understand what I was doing wrong, but it doesn't seem to me there is something evidently wrong.
The following is the code (last version) which initializes PJSIP:
public class SipService extends Service {
private Looper serviceLooper;
private ServiceHandler serviceHandler;
private final Messenger mMessenger = new Messenger(new IncomingHandler());
private LocalBroadcastManager localBroadcast;
private LifecycleBroadcastReceiver lifecycleBroadcastReceiver;
private boolean lastCheckConnected;
private Endpoint endpoint;
private LogWriter logWriter;
private EpConfig epConfig;
private final List<ManagedSipAccount> accounts = new ArrayList<>();
private final Map<String, Messenger> eventRegistrations = new HashMap<>();
#TargetApi(Build.VERSION_CODES.N)
#Override
public void onCreate() {
super.onCreate();
String userAgent = "MyApp";
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
String appLabel = (pInfo.applicationInfo.labelRes == 0 ? pInfo.applicationInfo.nonLocalizedLabel.toString() : getString(pInfo.applicationInfo.labelRes));
userAgent = appLabel + "/" + pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
Log.e("SipService", "Unable to get app version", e);
}
try {
endpoint = new MyAppEndpoint();
endpoint.libCreate();
epConfig = new EpConfig();
// Logging
logWriter = new PJSIPToAndroidLogWriter();
epConfig.getLogConfig().setWriter(logWriter);
epConfig.getLogConfig().setLevel(5);
// UA
epConfig.getUaConfig().setMaxCalls(4);
epConfig.getUaConfig().setUserAgent(userAgent);
// STUN
StringVector stunServer = new StringVector();
stunServer.add("stun.pjsip.org");
epConfig.getUaConfig().setStunServer(stunServer);
// General Media
epConfig.getMedConfig().setSndClockRate(16000);
endpoint.libInit(epConfig);
// UDP transport
TransportConfig udpCfg = new TransportConfig();
udpCfg.setQosType(pj_qos_type.PJ_QOS_TYPE_VOICE);
endpoint.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_UDP, udpCfg);
// TCP transport
TransportConfig tcpCfg = new TransportConfig();
//tcpCfg.setPort(5060);
endpoint.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_TCP, tcpCfg);
// TLS transport
TransportConfig tlsCfg = new TransportConfig();
endpoint.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_TLS, tlsCfg);
endpoint.libStart();
} catch (Exception e) {
throw new RuntimeException("Unable to initialize and start PJSIP", e);
}
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
lastCheckConnected = activeNetwork != null && activeNetwork.isConnected();
updateForegroundNotification();
startForeground(MyAppConstants.N_FOREGROUND_NOTIFICATION_ID, buildForegroundNotification());
localBroadcast = LocalBroadcastManager.getInstance(this);
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
serviceLooper = thread.getLooper();
serviceHandler = new ServiceHandler(serviceLooper);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// Register LifeCycleBroadcastReceiver to receive network change notification
// It seems it's mandatory to do it programmatically since Android N (24)
lifecycleBroadcastReceiver = new LifecycleBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(lifecycleBroadcastReceiver, intentFilter);
}
// Initialization
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs != null) {
try {
CodecInfoVector codecs = endpoint.codecEnum();
SharedPreferences.Editor editor = prefs.edit();
for (int i = 0; i < codecs.size(); i++) {
CodecInfo codec = codecs.get(i);
int priority = prefs.getInt("codecs.audio{" + codec.getCodecId() + "}", 0);
try {
endpoint.codecSetPriority(codec.getCodecId(), (short) priority);
codec.setPriority((short) priority);
} catch (Exception e) {
Log.e("SipService", "Unexpected error setting codec priority for codec " + codec.getCodecId(), e);
}
}
} catch (Exception e) {
Log.e("SipService", "Unexpected error loading codecs priorities", e);
}
}
}
#Override
public void onDestroy() {
for (Account acc : accounts) {
acc.delete();
}
accounts.clear();
try {
endpoint.libDestroy();
} catch (Exception e) {
e.printStackTrace();
}
endpoint.delete();
endpoint = null;
epConfig = null;
if (lifecycleBroadcastReceiver != null) {
unregisterReceiver(lifecycleBroadcastReceiver);
}
super.onDestroy();
}
.......
}
And the following is my Account class with creation and registration code:
public class ManagedSipAccount extends Account {
public final String TAG;
private final VoipAccount account;
private final PhoneAccountHandle handle;
private final SipService service;
private final AccountStatus status;
private final Map<Integer, VoipCall> calls = new HashMap<>();
private final Map<String, VoipBuddy> buddies = new HashMap<>();
private AccountConfig acfg;
private List<SrtpCrypto> srtpCryptos = new ArrayList<>();
private AuthCredInfo authCredInfo;
public ManagedSipAccount(SipService service, VoipAccount account, PhoneAccountHandle handle) {
super();
TAG = "ManagedSipAccount/" + account.getId();
this.service = service;
this.account = account;
this.handle = handle;
this.status = new AccountStatus(account.getUserName() + "#" + account.getHost());
acfg = new AccountConfig();
}
public void register(Map<String, String> contactParameters) throws Exception {
StringBuilder contactBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : contactParameters.entrySet()) {
contactBuilder.append(';');
contactBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
contactBuilder.append("=\"");
contactBuilder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
contactBuilder.append("\"");
}
StringBuilder logBuilder = new StringBuilder();
logBuilder.append("Registering: ");
logBuilder.append(account.getProtocol().name());
/*logBuilder.append('(');
logBuilder.append(service.getTransport(account.getProtocol()));
logBuilder.append(')');*/
if (account.isEncryptionSRTP()) {
logBuilder.append(" SRTP");
}
if (account.isIce()) {
logBuilder.append(" ICE");
}
Log.d(TAG, logBuilder.toString());
String idUri = "sip:" + account.getUserName();
if (!"*".equals(account.getRealm())) {
idUri += "#" + account.getRealm();
}
else {
idUri += "#127.0.0.1" /*+ account.getHost()*/;
}
acfg.setIdUri(idUri);
acfg.getRegConfig().setRegistrarUri("sip:" + account.getHost() + ":" + account.getPort() + ";transport=" + account.getProtocol().name().toLowerCase());
acfg.getRegConfig().setRetryIntervalSec(account.getRetryInterval());
acfg.getRegConfig().setRegisterOnAdd(false);
acfg.getSipConfig().setContactUriParams(contactBuilder.toString());
// NAT management
acfg.getNatConfig().setSipStunUse(pjsua_stun_use.PJSUA_STUN_USE_DEFAULT);
if (account.isIce()) {
acfg.getNatConfig().setIceEnabled(true);
acfg.getNatConfig().setIceAlwaysUpdate(true);
acfg.getNatConfig().setIceAggressiveNomination(true);
}
else {
acfg.getNatConfig().setSdpNatRewriteUse(1);
}
acfg.getMediaConfig().getTransportConfig().setQosType(pj_qos_type.PJ_QOS_TYPE_VOICE);
if (account.isEncryptionSRTP()) {
acfg.getMediaConfig().setSrtpUse(pjmedia_srtp_use.PJMEDIA_SRTP_MANDATORY);
acfg.getMediaConfig().setSrtpSecureSignaling(0);
//acfg.getMediaConfig().getSrtpOpt().setKeyings(new IntVector(2));
acfg.getMediaConfig().getSrtpOpt().getKeyings().clear();
acfg.getMediaConfig().getSrtpOpt().getKeyings().add(pjmedia_srtp_keying_method.PJMEDIA_SRTP_KEYING_SDES.swigValue());
acfg.getMediaConfig().getSrtpOpt().getKeyings().add(pjmedia_srtp_keying_method.PJMEDIA_SRTP_KEYING_DTLS_SRTP.swigValue());
acfg.getMediaConfig().getSrtpOpt().getCryptos().clear();
StringVector cryptos = Endpoint.instance().srtpCryptoEnum();
for (int i = 0; i < cryptos.size(); i++) {
SrtpCrypto crypto = new SrtpCrypto();
crypto.setName(cryptos.get(i));
crypto.setFlags(0);
srtpCryptos.add(crypto);
acfg.getMediaConfig().getSrtpOpt().getCryptos().add(crypto);
}
}
else {
acfg.getMediaConfig().setSrtpUse(pjmedia_srtp_use.PJMEDIA_SRTP_DISABLED);
acfg.getMediaConfig().setSrtpSecureSignaling(0);
}
authCredInfo = new AuthCredInfo("digest",
account.getRealm(),
account.getAuthenticationId() != null && account.getAuthenticationId().trim().length() > 0 ? account.getAuthenticationId() : account.getUserName(),
0,
account.getPassword());
acfg.getSipConfig().getAuthCreds().add( authCredInfo );
acfg.getIpChangeConfig().setHangupCalls(false);
acfg.getIpChangeConfig().setShutdownTp(true);
create(acfg);
ConnectivityManager cm = (ConnectivityManager)service.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnected();
if (isConnected) {
setRegistration(true);
}
}
#Override
public void onRegStarted(OnRegStartedParam prm) {
super.onRegStarted(prm);
Log.d(TAG, "Status: Registering...");
status.setStatus(AccountStatus.Status.REGISTERING);
service.updateStatus(this);
}
#Override
public void onRegState(OnRegStateParam prm) {
super.onRegState(prm);
try {
Log.d(TAG, "Registration state: " + prm.getCode().swigValue() + " " + prm.getReason());
AccountInfo ai = getInfo();
status.setStatus(ai.getRegIsActive() ? AccountStatus.Status.REGISTERED : AccountStatus.Status.UNREGISTERED);
Log.d(TAG, "Status: " + status.getStatus().name() + " " + super.getInfo().getUri());
service.updateStatus(this);
} catch (Exception e) {
e.printStackTrace();
}
}
.....
}
Finally, how I answer the code at the moment in a class which extends the PJSIP's Call class:
#Override
public void answerCall() {
Log.d(TAG, "Answering call...");
CallOpParam prm = new CallOpParam(true);
prm.setStatusCode(pjsip_status_code.PJSIP_SC_OK);
prm.getOpt().setAudioCount(1);
prm.getOpt().setVideoCount(0);
try {
this.answer(prm);
} catch (Exception e) {
e.printStackTrace();
}
}
I also tried with new CallOpParam(); with just the status code and nothing else, but nothing changes.
One note: I created the IdUri as sip:username#127.0.0.1 because without the host the resulting contact was and I thought that the missing user part may be the cause of the issue or part of it.
The following is the trace of the app <-> my Asterisk server communication during call (linked because of content length exceed).
https://gist.github.com/ivano85/a212ddc9a808f3cd991234725c2bdb45
The ServerIp is an internet public IP, while the MyIp[5.XXX.XXX.XXX] is my phone's public IP.
As you can see from the log, my app sends a 100 Trying, then a 180 Ringing when the phone rings, then the user answers and the app sends a 200 OK. The server replies with a ACK message (I would say it's not a NAT issue, because PJSIP receives the ACK). I see the same from Asterisk.
After this I would expect the call goes from PJSIP_INV_STATE_CONNECTING to PJSIP_INV_STATE_CONFIRMED, but it does not happen, so PJSIP continues to send a 200 OK and receive the ACK every about 2 seconds, until the call times out after 32 seconds and PJSIP disconnects the call (sending a BYE).
I'm starting to think that PJSIP just ignores ACK messages and just has a wrong behaviour. Please help me to understand what is happening here. I would appreciate it so much!
Obviously let me know if you think that more details are needed.

How to make messages show up automatically when recieved in Android SMS app?

So I have this pretty simple app. It sends encrypted SMS messages to the specified phone number. It works swell, but I am having issues finding a way to make the recieved messages automatically show up in the message log. I currectly have a "refresh" button that updates the message log if a new message is available. I don't want to have to use a refresh button, I want the message to simply show up as it is received.
The way the app works is, it takes the message to be sent from the textbox and encrypts it. It then sends the message and when received, it decrypts and stores in a variable and presents in the message log (after I press "refresh").
I have tried many searches on google but can not find something useful because the words are too sensetive. I usually find links to people not being able to receive messages or just links to download messaging apps.
Here is some of my code. This is the receive sms part.
public class SmsReceiver extends BroadcastReceiver
{
public static String decrypted = "";
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str ="";
String info = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
info += "SMS from " + msgs[i].getOriginatingAddress();
info += " : ";
str += msgs[i].getMessageBody().toString();
if (i==msgs.length-1 && MainActivity.locked == true){
try {
decrypted = AESHelper.decrypt(MainActivity.seed, str);
} catch (Exception e) {
e.printStackTrace();
}
MainActivity.rand = Math.random();
MainActivity.seed = String.valueOf(MainActivity.rand);
decrypted = info + decrypted;
info = "";
MainActivity.locked = false;
}
}
}
So, in my main activity, I have the refresh button set to check the length of decrypted. If length of decrypted > 0 then I take decrypted's content and display them in the message log.
There are multiple ways to do this. Simple way would be to use TimerTask that runs every second in your MainActivity to check the length of 'decrypted' variable. Timertask does not run on ui thread. But since you are using it only to check the length of a variable you should be fine. If you need help with timertask, use my example below:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new SpecificTask(), 1000, 200);
But you have to define your SpecificTask() class...
private Specific Task extends TimerTask{
#Override
public void run() {
if(decrypted.length()>0){
//do refresh here but make sure you run this code onuithread
//just use runonuithread...
}
}
}
Or you could just use a handler object...
boolean mStopHandler = false;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
if (!mStopHandler) {
if(decrypted.length()>0){
//refreshlayout code
}
handler.postDelayed(this, 500);
}
}
};
// start your handler with:
handler.post(runnable);

isReachable not working in android studio

I am using XBMC android source code and now try to extract some code to new xbmc android project. When i try to connect to a ip address and check whether it is reachable using isReachable(), it is throwing a NetworkOnMainThreadException but same source code(in XBMC source code that is i downloded from the git) it is working fine,
This is the source code i'm working on
Handler handler = new Handler(){
public void handleMessage(android.os.Message message){
if(message.getData().containsKey(MacAddressResolver.MESSAGE_MAC_ADDRESS)){
String mac = message.getData().getString(MacAddressResolver.MESSAGE_MAC_ADDRESS);
if(!mac.equals("")) {
mMacAddrView.setText(mac);
Toast toast = Toast.makeText(getContext(), "Updated MAC for host: " + mHostView.getText().toString() + "\nto: " + mac, Toast.LENGTH_SHORT);
toast.show();
}
}
}
};
public class MacAddressResolver implements Runnable{
private String mHost = null;
private String mMac = null;
private Handler mHandler;
public static final String MESSAGE_MAC_ADDRESS = "MAC_ADDRESS";
public MacAddressResolver(String ipString, Handler handler){
mHost = ipString;
mHandler = handler;
}
public void run(){
mMac = arpResolve(mHost);
Bundle bundle = new Bundle();
bundle.putString(MESSAGE_MAC_ADDRESS, mMac);
Message message = new Message();
message.setData(bundle);
mHandler.sendMessage(message);
}
private String arpResolve(String host){
System.out.println("ARPRESOLVE HOST: " + host);
try{
//Parse it as a proper InetAddress - it might be a hostname. We don't know yet.
InetAddress inet = InetAddress.getByName(host);
//initiate some sort of traffic to ensure we get an arp entry (if we're on same subnet, that is...)
inet.isReachable(500); //timeout of 500ms. just to trigger the arp resolution process
//Get the official string representation of the resolved ip address
String ipString = inet.getHostAddress();
BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"));
String line = "";
while(true){
line = br.readLine();
if (line == null)
break;
if(line.startsWith(ipString)){
br.close();
System.out.println("ARPRESOLVE MAC:\n" + line);
return line.split("\\s+")[3]; // 4th word, separated by "whitespace"
}
}
br.close();
return "";
}catch(Exception e){
return "";
}
}
}
and i also put these two permission in my AndroidManifest.xml file
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="13" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I don't know, what is the problem and how can i fix it?
NetworkOnMainThreadException exception means that you are doing some Networking Work on MainThread (which will overload that Thread and throw an Exception).
So, you have to move that Networking Code to the Background Thread(another thread other then Main Thread).
AsyncTask
is a good example to handle such things

Unable to send MMS using SmsManager

I am trying to make an app that would send a MMS without using the native Android messaging app. I followed the example here. My log statements seem to be correctly printing, but I can't figure out why the MMS is not being sent.
Also on a different note, I am a bit confused about where in the example the attachment (like an image) is being selected to send as MMS. I tried to import the demo into Android Studio but I ran into issues.
My function for sending MMS is below:
public void sendMMS() {
Log.d(TAG, "sendMMS()");
Random random = new Random();
final String fileName = "send." + String.valueOf(Math.abs(random.nextLong())) + ".dat";
final File mSendFile = new File(mContext.getCacheDir(), fileName);
// Making RPC call in non-UI thread
AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
#Override
public void run() {
final byte[] pdu = buildPdu();
Uri writerUri = (new Uri.Builder())
.authority("com.example.appname")
.path(fileName)
.scheme(ContentResolver.SCHEME_CONTENT)
.build();
Log.d(TAG, "sendMMS(): Uri: " + writerUri.toString());
FileOutputStream writer = null;
Uri contentUri = null;
try {
writer = new FileOutputStream(mSendFile);
writer.write(pdu);
contentUri = writerUri;
Log.d(TAG, "sendMMS(): just wrote file");
} catch (final IOException e) {
Log.d(TAG, "sendMMS(): FAILED: couldn't write file");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
if (contentUri != null) {
SmsManager.getDefault().sendMultimediaMessage(mContext, contentUri, null, null, null);
Log.d(TAG, "sendMMS(): just sent");
} else {
Log.d(TAG, "sendMMS(): FAILED: couldn't write file so didn't send");
}
}
});
}
Helper functions
private byte[] buildPdu() {
final SendReq req = new SendReq();
// from
final String lineNumber = getSimNumber();
if (!TextUtils.isEmpty(lineNumber)) {
req.setFrom(new EncodedStringValue(lineNumber));
}
// to
String[] destsArray = mDestList.toArray(new String[mDestList.size()]);
EncodedStringValue[] encodedNumbers = EncodedStringValue.encodeStrings(destsArray);
if (encodedNumbers != null) {
req.setTo(encodedNumbers);
}
// date
req.setDate(System.currentTimeMillis() / 1000);
// body
PduBody body = new PduBody();
// message text
final int size = addMessagePart(body, true/* add text smil */);
req.setBody(body);
// message size
req.setMessageSize(size);
// message class
req.setMessageClass(PduHeaders.MESSAGE_CLASS_PERSONAL_STR.getBytes());
// expiry
req.setExpiry(DEFAULT_EXPIRY_TIME);
try {
// priority
req.setPriority(DEFAULT_PRIORITY);
// delivery report
req.setDeliveryReport(PduHeaders.VALUE_NO);
// read report
req.setReadReport(PduHeaders.VALUE_NO);
} catch (InvalidHeaderValueException e) {}
return new PduComposer(mContext, req).make();
}
private String getSimNumber() {
TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getLine1Number();
}
private int addMessagePart(PduBody pb, boolean addTextSmil) {
PduPart part = new PduPart();
part.setCharset(CharacterSets.UTF_8);
part.setContentType(ContentType.TEXT_PLAIN.getBytes());
part.setContentLocation(TEXT_PART_FILENAME.getBytes());
int index = TEXT_PART_FILENAME.lastIndexOf(".");
String contentId = (index == -1) ? TEXT_PART_FILENAME : TEXT_PART_FILENAME.substring(0, index);
part.setContentId(contentId.getBytes());
part.setData(mMessage.getBytes());
pb.addPart(part);
if (addTextSmil) {
String smil = String.format(sSmilText, TEXT_PART_FILENAME);
addSmilPart(pb, smil);
}
return part.getData().length;
}
private void addSmilPart(PduBody pb, String smil) {
PduPart smilPart = new PduPart();
smilPart.setContentId("smil".getBytes());
smilPart.setContentType(ContentType.APP_SMIL.getBytes());
smilPart.setContentLocation("smil.xml".getBytes());
smilPart.setData(smil.getBytes());
pb.addPart(0, smilPart);
}
Relevant parts of my manifest
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Relevant instance variables
private final long DEFAULT_EXPIRY_TIME = 7 * 24 * 60 * 60;
private final String TEXT_PART_FILENAME = "text_0.txt";
private final int DEFAULT_PRIORITY = PduHeaders.PRIORITY_NORMAL;
private String mMessage;
private ArrayList<String> mDestList;
private Context mContext;
private static final String sSmilText =
"<smil>" +
"<head>" +
"<layout>" +
"<root-layout/>" +
"<region height=\"100%%\" id=\"Text\" left=\"0%%\" top=\"0%%\" width=\"100%%\"/>" +
"</layout>" +
"</head>" +
"<body>" +
"<par dur=\"8000ms\">" +
"<text src=\"%s\" region=\"Text\"/>" +
"</par>" +
"</body>" +
"</smil>";
I already do input checks, so by the time sendMMS() is called, my message and destList are not null.
The flow should be as such:
Create the Mms send-request - new SendReq() and config its date, body, to, etc.
Create the Mms body - new PduBody().
Create Parts via new PduPart() for each attachment, and add to the body: body.addPart(pdu)
Add the body to the request - req.setBody(body)
Convert the send-request to a byte[] ready to be sent by calling new PduComposer(context, mySendReq).make() - note that you'll need to copy lots of code from Android's source code to get the PduComposer class.
Now's the interesting part - you save the byte[] to a local file accessible to your app only, and add ContentProvider class that allows other apps to request access to your file, this is MmsFileProvider class in the sample app, don't forget to declare your provider in your manifest file.
Now, when you call the SmsManager.sendMultimediaMessage api, your file provider will wake up to serve the file containing the pdu bytes to the system SmsManager that will read it and send it on the wire.
Having that said, this API is only working for me on some devices (e.g. Nexuses), but not on some others (e.g. HTC One).
See my SO question here:
SmsManager MMS APIs on HTC/LG

android client socket is not receiving data

I have a tcp server which is not in java also its a hardware device , I need to send and receve the data ,
I am connecting with server and sending some configuration data using following code
this.clientSocket=new Socket("198.168.1.17",9999);
this.os=new DataOutputStream(this.clientSocket.getOutputStream());
this.in=new DataInputStream(this.clientSocket.getInputStream());
System.out.println("Conncted");
char data[]={0x03,0x03,0x00};
byte b[]=new byte[data.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) data[i];
}
try {
os.write(b);
Device receives data correctly , now in my tcp client i am not able to receive data , though i write following code just after above code
int size =in.available();
byte data1[]=new byte[size];
// in.read(data1);
String str=new String(data1);
System.out.println("Reading data:"+str);
It only shows reading data , and string has not data
also i tried about code in thread
public void run(){
try{
while(true){
int size =in.available();
byte data[]=new byte[size];
in.read(data);
String str=new String(data);
System.out.println("Reading data:"+str);
}
in thread it only shows reading data ,
Please help how can i get data from the server also please note server is built in i can not change the server code
what available() method do in code "int size =in.available();"????????
Solution may be:
available() method return 0 so you are not able to receive data.
use this code for receiving data from socket. write this code before onCreate.
private EditText mInputMessageView;
private Emitter.Listener onNewMessage = new Emitter.Listener() {
#Override
public void call(final Object... args) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
String message;
try {
username = data.getString("username");
message = data.getString("message");
} catch (JSONException e) {
return;
}
// add the message to view
addMessage(username, message);
}
});
}
};

Categories

Resources