My app
Hello, I have designed an application that receives messages and device information as shown in the image and show the TextView,
But now how to get messages and device information to an example api file.php in the host?
For example this is my php file in host:
http://example.com/api/file.php
How i Send it?!!
Please help to me i can complete the app
This is my MainActivity.java
codes:
setContentView(R.layout.main);
num = (TextView) findViewById(R.id.sender);
msg = (TextView) findViewById(R.id.content);
manufacturerTxt = findViewById(R.id.DeviceName);
modelTxt = findViewById(R.id.DeviceModel);
versionTxt = findViewById(R.id.AndroidVersion);
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
String version = Build.VERSION.RELEASE;
int sdk = Build.VERSION.SDK_INT;
String hardware = Build.HARDWARE;
manufacturerTxt.setText(manufacturer);
modelTxt.setText(model);
versionTxt.setText(version);
receiveFilter = new IntentFilter();
receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
messageReceiver = new MessageReceiver();
registerReceiver(messageReceiver, receiveFilter);
to = (EditText) findViewById(R.id.to);
msgInput = (EditText) findViewById(R.id.msg_input);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS)== PackageManager.PERMISSION_GRANTED)
{
MessageSent();
}
else
{
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.SEND_SMS},100);
}
}
});
}
private void MessageSent() {
String num=to.getText().toString().trim();
String msg=msgInput.getText().toString().trim();
if(!num.equals("") && !msg.equals(""))
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(num, null,msg, null, null);
Toast.makeText(getApplicationContext(),"sent",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(),"fill the fields",Toast.LENGTH_SHORT).show();
}
}
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(messageReceiver);
}
class MessageReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus"); // Retrieve SMS messages
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
String address = messages[0].getOriginatingAddress();
String fullMessage = "";
for (SmsMessage message : messages) {
fullMessage += message.getMessageBody();
}
num.setText(address);
msg.setText(fullMessage);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==100 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
MessageSent();
}
else {
Toast.makeText(getApplicationContext(),"permission denied",Toast.LENGTH_LONG).show();
}}
}
}
To use REST APIs, you should use a library called Retrofit or Volley.
You can check these two libraries and get an idea as to how to send messages over a HTTP REST API.
Reference:
Volley
Retrofit
Related
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();
}
I wanted my Android to communicate with an Arduino using an USB host. I've tried many references but can't seem to send any char to my Arduino. I can detect my Arduino but sending char or string to it is frustrating. Here are my codes:
MainActivity.java
public class MainActivity extends AppCompatActivity {
UsbDevice device=null;
UsbManager manager=null;
PendingIntent mPermissionIntent;
UsbInterface intf;
UsbEndpoint endpoint;
UsbDeviceConnection connection;
Button find;
Button send;
TextView hello;
UsbManager mUsbManager;
private static final String ACTION_USB_PERMISSION =
"com.android.example.USB_PERMISSION";
private byte[] bytes;
private static int TIMEOUT = 0;
private boolean forceClaim = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find = (Button) findViewById(R.id.Find);
send = (Button) findViewById(R.id.Send);
hello = (TextView) findViewById(R.id.hello);
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hello.setText("");
checkInfo();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(device!=null) {
intf = device.getInterface(0);
endpoint = intf.getEndpoint(0);
connection = mUsbManager.openDevice(device);
hello.setText("Kirim");
String kirim = "a";
bytes = kirim.getBytes();
connection.claimInterface(intf, forceClaim);
connection.bulkTransfer(endpoint, bytes, bytes.length, 0);
}
else{
Toast.makeText(MainActivity.this,"Device ==
null",Toast.LENGTH_SHORT);
}
}
});
private void checkInfo(){
manager=(UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this,0,new
Intent(ACTION_USB_PERMISSION),0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver,filter);
HashMap<String,UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
String i="";
int j=0;
while(deviceIterator.hasNext()){
device = deviceIterator.next();
manager.requestPermission(device,mPermissionIntent);
i += "\n" + "DeviceID: " + device.getDeviceId() + "\n"
+ "DeviceName: " + device.getDeviceName() + "\n"
+ "DeviceClass: " + device.getDeviceClass() + " - "
+ "DeviceSubClass: " + device.getDeviceSubclass() + "\n"
+ "VendorID: " + device.getVendorId() + "\n"
+ "ProductID: " + device.getProductId() + "\n";
j++;
}
hello.setText(i);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// call method to set up device communication
}
} else {
Log.d("ERROR", "permission denied for device " +
device);
}
}
}
}
};
}
I iterate using a find button and send using a send button. The iteration went just fine, but the sending didn't work. I needed to send just a character to the Arduino. My phone supports OTG and had been tested using other serial communication application to send char to Arduino and it works just fine.
Thanks in advance
using the usb serial lib in releases section at: https://github.com/felHR85/UsbSerial then import the lib and install dependencies as shown in the url. For solving the problem you can create a service class that handles usb related stuff (look at usb host android documentation for details: https://developer.android.com/guide/topics/connectivity/usb/host.html
as follows:
public class UsbService extends Service {
public static final String TAG = "UsbService";
public static final String ACTION_USB_READY = "com.felhr.connectivityservices.USB_READY";
public static final String ACTION_USB_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
public static final String ACTION_USB_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
public static final String ACTION_USB_NOT_SUPPORTED = "com.felhr.usbservice.USB_NOT_SUPPORTED";
public static final String ACTION_NO_USB = "com.felhr.usbservice.NO_USB";
public static final String ACTION_USB_PERMISSION_GRANTED = "com.felhr.usbservice.USB_PERMISSION_GRANTED";
public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "com.felhr.usbservice.USB_PERMISSION_NOT_GRANTED";
public static final String ACTION_USB_DISCONNECTED = "com.felhr.usbservice.USB_DISCONNECTED";
public static final String ACTION_CDC_DRIVER_NOT_WORKING = "com.felhr.connectivityservices.ACTION_CDC_DRIVER_NOT_WORKING";
public static final String ACTION_USB_DEVICE_NOT_WORKING = "com.felhr.connectivityservices.ACTION_USB_DEVICE_NOT_WORKING";
public static final int MESSAGE_FROM_SERIAL_PORT = 0;
public static final int CTS_CHANGE = 1;
public static final int DSR_CHANGE = 2;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private static final int BAUD_RATE = 9600; // BaudRate. Change this value if you need
public static boolean SERVICE_CONNECTED = false;
private IBinder binder = new UsbBinder();
private UsbService context;
private Handler mHandler;
private UsbManager usbManager;
private UsbDevice device;
private UsbDeviceConnection connection;
private UsbSerialDevice serialPort;
private boolean serialPortConnected;
/*
* Data received from serial port will be received here. Just populate onReceivedData with your code
* In this particular example. byte stream is converted to String and send to UI thread to
* be treated there.
*/
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
#Override
public void onReceivedData(byte[] arg0) {
try {
String data = new String(arg0, "UTF-8");
if (mHandler != null)
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
/*
* State changes in the CTS line will be received here
*/
private UsbSerialInterface.UsbCTSCallback ctsCallback = new UsbSerialInterface.UsbCTSCallback() {
#Override
public void onCTSChanged(boolean state) {
if(mHandler != null)
mHandler.obtainMessage(CTS_CHANGE).sendToTarget();
}
};
/*
* State changes in the DSR line will be received here
*/
private UsbSerialInterface.UsbDSRCallback dsrCallback = new UsbSerialInterface.UsbDSRCallback() {
#Override
public void onDSRChanged(boolean state) {
if(mHandler != null)
mHandler.obtainMessage(DSR_CHANGE).sendToTarget();
}
};
/*
* Different notifications from OS will be received here (USB attached, detached, permission responses...)
* About BroadcastReceiver: http://developer.android.com/reference/android/content/BroadcastReceiver.html
*/
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) // User accepted our USB connection. Try to open the device as a serial port
{
Intent intent = new Intent(ACTION_USB_PERMISSION_GRANTED);
arg0.sendBroadcast(intent);
connection = usbManager.openDevice(device);
new ConnectionThread().start();
} else // User not accepted our USB connection. Send an Intent to the Main Activity
{
Intent intent = new Intent(ACTION_USB_PERMISSION_NOT_GRANTED);
arg0.sendBroadcast(intent);
}
} else if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
if (!serialPortConnected)
findSerialPortDevice(); // A USB device has been attached. Try to open it as a Serial port
} else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {
// Usb device was disconnected. send an intent to the Main Activity
Intent intent = new Intent(ACTION_USB_DISCONNECTED);
arg0.sendBroadcast(intent);
if (serialPortConnected) {
serialPort.close();
}
serialPortConnected = false;
}
}
};
/*
* onCreate will be executed when service is started. It configures an IntentFilter to listen for
* incoming Intents (USB ATTACHED, USB DETACHED...) and it tries to open a serial port.
*/
#Override
public void onCreate() {
this.context=this;
serialPortConnected = false;
UsbService.SERVICE_CONNECTED = true;
setFilter();
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
findSerialPortDevice();
}
/* MUST READ about services
* http://developer.android.com/guide/components/services.html
* http://developer.android.com/guide/components/bound-services.html
*/
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
serialPort.close();
unregisterReceiver(usbReceiver);
UsbService.SERVICE_CONNECTED = false;
}
/*
* This function will be called from MainActivity to write data through Serial Port
*/
public void write(byte[] data) {
if (serialPort != null)
serialPort.write(data);
}
public void setHandler(Handler mHandler) {
this.mHandler = mHandler;
}
private void findSerialPortDevice() {
// This snippet will try to open the first encountered usb device connected, excluding usb root hubs
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
// first, dump the hashmap for diagnostic purposes
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
Log.d(TAG, String.format("USBDevice.HashMap (vid:pid) (%X:%X)-%b class:%X:%X name:%s",
device.getVendorId(), device.getProductId(),
UsbSerialDevice.isSupported(device),
device.getDeviceClass(), device.getDeviceSubclass(),
device.getDeviceName()));
}
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
int devicePID = device.getProductId();
// if (deviceVID != 0x1d6b && (devicePID != 0x0001 && devicePID != 0x0002 && devicePID != 0x0003) && deviceVID != 0x5c6 && devicePID != 0x904c) {
if (UsbSerialDevice.isSupported(device)) {
// There is a supported device connected - request permission to access it.
requestUserPermission();
break;
} else {
connection = null;
device = null;
}
}
if (device==null) {
// There are no USB devices connected (but usb host were listed). Send an intent to MainActivity.
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
} else {
Log.d(TAG, "findSerialPortDevice() usbManager returned empty device list." );
// There is no USB devices connected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
}
private void setFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(ACTION_USB_DETACHED);
filter.addAction(ACTION_USB_ATTACHED);
registerReceiver(usbReceiver, filter);
}
/*
* Request user permission. The response will be received in the BroadcastReceiver
*/
private void requestUserPermission() {
Log.d(TAG, String.format("requestUserPermission(%X:%X)", device.getVendorId(), device.getProductId() ) );
PendingIntent mPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, mPendingIntent);
}
public class UsbBinder extends Binder {
public UsbService getService() {
return UsbService.this;
}
}
/*
* A simple thread to open a serial port.
* Although it should be a fast operation. moving usb operations away from UI thread is a good thing.
*/
private class ConnectionThread extends Thread {
#Override
public void run() {
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) {
serialPortConnected = true;
serialPort.setBaudRate(BAUD_RATE);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
/**
* Current flow control Options:
* UsbSerialInterface.FLOW_CONTROL_OFF
* UsbSerialInterface.FLOW_CONTROL_RTS_CTS only for CP2102 and FT232
* UsbSerialInterface.FLOW_CONTROL_DSR_DTR only for CP2102 and FT232
*/
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
serialPort.getCTS(ctsCallback);
serialPort.getDSR(dsrCallback);
//
// Some Arduinos would need some sleep because firmware wait some time to know whether a new sketch is going
// to be uploaded or not
//Thread.sleep(2000); // sleep some. YMMV with different chips.
// Everything went as expected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_USB_READY);
context.sendBroadcast(intent);
} else {
// Serial port could not be opened, maybe an I/O error or if CDC driver was chosen, it does not really fit
// Send an Intent to Main Activity
if (serialPort instanceof CDCSerialDevice) {
Intent intent = new Intent(ACTION_CDC_DRIVER_NOT_WORKING);
context.sendBroadcast(intent);
} else {
Intent intent = new Intent(ACTION_USB_DEVICE_NOT_WORKING);
context.sendBroadcast(intent);
}
}
} else {
// No driver for given device, even generic CDC driver could not be loaded
Intent intent = new Intent(ACTION_USB_NOT_SUPPORTED);
context.sendBroadcast(intent);
}
}
}
}
then in your main activity put this snippets:
java
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private UsbService usbService;
public TextView display;
private EditText editText;
private MyHandler mHandler;
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
// Toast.makeText(getApplicationContext(),"dentro on service connected " + usbService, Toast.LENGTH_SHORT).show();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.operacion);
mHandler = new MyHandler(this);
// your stuff here
#Override
public void onResume() {
super.onResume();
// Toast.makeText(getApplicationContext(),"on resume ", Toast.LENGTH_SHORT).show();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
// Toast.makeText(getApplicationContext(),"despues de start y weas ", Toast.LENGTH_SHORT).show();
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
// Toast.makeText(getApplicationContext(),"start1", Toast.LENGTH_SHORT).show();
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
// Toast.makeText(getApplicationContext(),"dp metodo start", Toast.LENGTH_SHORT).show();
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
public void getCurrentTimeUsingDate(){
String currentDateTimeString2 = DateFormat.getDateInstance().format(new Date());
TextView txtView3 = (TextView) findViewById(R.id.textView4);
txtView3.setText(""+currentDateTimeString2);
}
private static class MyHandler extends Handler {
private final WeakReference<Pag4> mActivity;
public MyHandler(Pag4 activity) {
mActivity = new WeakReference<>(activity);
}
Integer conta = 0;
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
conta++;
break;
case UsbService.CTS_CHANGE:
Toast.makeText(mActivity.get(), "CTS_CHANGE",Toast.LENGTH_LONG).show();
break;
case UsbService.DSR_CHANGE:
Toast.makeText(mActivity.get(), "DSR_CHANGE",Toast.LENGTH_LONG).show();
break;
}
}
}
}
you make a button (btn3 in the example) and then add the listener as follows:
java
bt3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String auxi2="1"; // put whatever you need to send here
if (!auxi2.equals("")) {
String data = auxi2;
if (usbService != null) { // if UsbService was correctly binded, Send data
usbService.write(data.getBytes());
// Toast.makeText(getApplicationContext(),"auxi2 escrito"+ auxi2, Toast.LENGTH_SHORT).show();
}
}
}
});
Hope is clear, I assume you know how to import libs, and make a button, put the permission in manifiest, dependencies. Details about this in android doc link already posted upper in my answer.
I have an SMS reader application and i am showing the senderno and message body into the Custom Listview. For the incoming messages i have registered a broadcast receiver and populating the listView.
Whenever a new message is coming in the broadcast Receiver i am able to get it but I want to this data to be passed onto the activity.
The code snippets are :
MainActvity.java
public class MainSmsActivity extends Activity{
private ListView smsList;
SmsAdapter smsAdapter;
private SmsDao smsDao;
private List<SmsDao> smsDataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_demo);
smsDataList = new ArrayList<SmsDao>();
Intent intent = new Intent();
intent.setAction("com.mobile.sms.IncomingSms");
sendBroadcast(intent);
populateSms();
}
public void populateSms(){
Uri inboxURI = Uri.parse("content://sms/inbox");
String[] reqCols = new String[] { "_id", "address", "body", "date" };
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(inboxURI, reqCols, null, null, null);
smsDataList.clear();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
smsDao = new SmsDao();
smsDao.setMessageBody(cursor.getString(1));
smsDao.setSenderNo(cursor.getString(2));
smsDao.setMessageTime(cursor.getLong(3));
smsDataList.add(smsDao);
}
smsAdapter = new SmsAdapter(this,smsDataList);
smsList.setAdapter(smsAdapter);
smsAdapter.notifyDataSetChanged();
cursor.close();
}
}
IncomingSms.Java
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
int duration = Toast.LENGTH_LONG; // HERE I WANT TO SEND MESSAGE BODY TO THE MAIN ACTIVITY CLASS
Toast toast = Toast.makeText(context,
"senderNum: " + senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
I am able to receive all the messages intially into the list view but I want that the ListView should get automatically updated as soon as new message arrives.
In your broadcasereceiver do something like this: (use that intent)
public class SMSReceiver extends BroadcastReceiver {
public static final String NOTIFICATION = "receiver_sms";
#Override
public void onReceive(Context context, Intent intent) {
Log.i("onReceive methode", "new SMS Comming");
Bundle myBundle = intent.getExtras();
SmsMessage[] messages = null;
String strMessage = "", address = "";
abortBroadcast();
if (myBundle != null) {
// get message in pdus format(protocol description unit)
Object[] pdus = (Object[]) myBundle.get("pdus");
// create an array of messages
messages = new SmsMessage[pdus.length];
Log.i("onReceive methode", "new SMS Comming");
for (int i = 0; i < messages.length; i++) {
// Create an SmsMessage from a raw PDU.
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// get the originating address (sender) of this SMS message in
// String form or null if unavailable
address = messages[i].getOriginatingAddress();
// get the message body as a String, if it exists and is text
// based.
strMessage += messages[i].getMessageBody();
strMessage += "\n";
}
// show message in a Toast
}
// this is what you need
Intent broadcast = new Intent(NOTIFICATION);
broadcast.putExtra("data", strMessage);
LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast);
}
and then register ur receiver in ur activity
public BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(tag, "SMS Received.");
// Intent i = getIntent();
Bundle b = intent.getBundleExtra("SMS");
// String bun = b.getString("MyData");
Log.i(tag, "Bundle: " + b);
String str = intent.getStringExtra("data");
parseSMSData(str);
}
};
and then in onResume():
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter(SMSReceiver.NOTIFICATION));
}
and in onDestroy() you must unregister that receiver like this:
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onDestroy();
}
and also don't forget to add this in ur manifest file in application tag:
<receiver android:name=".SMSBroadcastReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
register your service in OnResume() then you can access easily within your class,
#Override
public void onResume()
{
super.onResume();
this.registerReceiver(this.yourservice, new IntentFilter("your service type"));
}
and unregister the service in your onpause()
#Override
public void onPause() {
super.onPause();
try
{
this.unregisterReceiver(this.your service);
}
catch(Exception e)
{
e.printStackTrace();
}
}
add the your broadcast receiver in your activity ,
private WakefulBroadcastReceiver IncomingSms = new WakefulBroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//use your receiver content
}
Put the following class in your MainSmsActivity so that you should be able to process your list.
private class IncomingSms extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("incomingSms")) {
//your impl here
}
}
}
and in onCreate() of your MainSmsActivity activity, place the following code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
IncomingSms broadcastReceiver = new IncomingSms(); // declare it outside so that it should be accessible in onDestroy()
IntentFilter intentFilter = new IntentFilter("incomingSms");
registerReceiver(broadcastReceiver , intentFilter);
}
and in onDestroy() place the following code
#Override
protected void onDestroy() {
if (broadcastReceiver != null) {
unregisterReceiver(broadcastReceiver);
}
super.onDestroy();
}
I am working on an application that needs to read an incoming message. Now, i found out that i need to use the onReceive method from the BroadcastReceiver class. Now i got to know that java does not allow extending two classes, so how do i get it working, i have been stuck on this from a long time, please help! Also if there is some other way to do this, please do quote.
public class SMS extends Activity {
Button btnSendSMS;
EditText txtPhoneNo;
EditText txtMessage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sms);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String phoneNo = txtPhoneNo.getText().toString();
if (phoneNo.length()>0)
sendSMS(phoneNo, phoneNo);
else
Toast.makeText(getBaseContext(),
"Please enter a valid Phone Number.",
Toast.LENGTH_SHORT).show();
}
});
}
private void sendSMS(String phoneNumber, String message)
{
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, SMS.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
}
Context context = getApplicationContext();
Intent intent = new Intent();
object.onReceive(context, intent); }
class SMSBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SMSBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());
Toast.makeText(context, "HI", Toast.LENGTH_SHORT).show();
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
if (messages.length > -1) {
Toast.makeText(context, "Message recieved: " + messages[0].getMessageBody(), 7000).show();
}
}
}
} }
You don't need to extend two classes (which is not possible and never required in java) to achieve your goal. For getting the last message simply create a static message variable, lets say in your SMSBroadcastReceiver and set that variable to latest message received in onreceive. This static variable can be accessed throughout your app using SmsReceiver.latestmessage
I have a receiver that is called whenever an SMS is received
public class SMSReceiver extends BroadcastReceiver {
private SharedPreferences prefs;
private String prefName = "MyPref";
private static final String NUMBER_KEY = "number";
#Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
String Sender = null;
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]);
Sender = msgs[i].getOriginatingAddress();
}
prefs = context
.getSharedPreferences(prefName, Context.MODE_PRIVATE);
String phoneNumber = (String) prefs.getString(NUMBER_KEY, "");
// If the sender of the SMS just received is the same as one chosen
// earlier
if (Sender.equals(phoneNumber)) {
Toast.makeText(context, "text message received",
Toast.LENGTH_LONG).show();
// ---Launch the minderActivity even when the app is not in the
// foreground---
Intent minderActivityIntent = new Intent(context, Minder.class);
minderActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(minderActivityIntent);
// ---send a broadcast intent to update the SMS received in the
// activity---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("Sender", Sender);
context.sendBroadcast(broadcastIntent);
}
}
}
}
I register the receiver in an activity called "minder" using a button
registerReceiver(intentReceiver, intentFilter);
In this "minder" activity I also have a BroadcastReceiver
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// ---gather up all the necessary user input---
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
final Button btn2 = (Button) findViewById(R.id.btnContacts);
String phoneNumber = (String) prefs.getString(NUMBER_KEY, "");
String messageChosen = (String) prefs.getString(MESSAGE_KEY, "");
String delay = (String) prefs.getString(DELAY_KEY, "");
String Sender = (String) intent.getExtras().getString("Sender");
if (Sender.equals(phoneNumber)) {
sendSMS(phoneNumber, messageChosen, delay);
}
}
};
All of the permissions are defined in the manifest.
Unfortunately when I test the receiver (i.e. send an sms to the phone, after the receiver has been registered, from the number that is defined as "phoneNumber") the app performs no action. Any ideas what is missing from my above code?