I have an application which listens incoming calls. The application has a database with a its own contact names and numbers.
When you get an incoming call, if the incoming number(say,1234) is not available in native contact database, the application checks it in it's database and finds the contact name from the database if number is available in it. (say, xyz)...
My aim is to refresh the incall screen with new contact name saying "xyz calling.." instead of "1234 calling.."..
Is it possible??..
Its not possible to refresh Incoming call screen but u can display desired name by fetching your own database... For that u need run ur own thread on incoming call screen, I used Timer and Timer Task to do so here is example
Your BroadcastReceiver should contain
ServiceReceiver extends BroadcastReceiver{
#Override
public void onReceive(final Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String state = extras.getString(TelephonyManager.EXTRA_STATE);
incomingNumber = extras.getString("incoming_number");
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
/********** Fetch name from your DB ************/
if (Name not present in your DB)
{
return;
}
if(present){
incomingCallTimer = new Timer();
ToastMessageHandler messageHandler = new ToastMessageHandler(context, contactName);
incomingCallTimer.schedule(new ToastTimer(messageHandler), 1000, 2000);
}
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
// callActionHandler.removeCallbacks(runRingingActivity);
// setResultCode(Activity.RESULT_CANCELED);
try{
incomingCallTimer.cancel();
} catch (Exception e) {
}
}
}
class ToastTimer extends TimerTask {
ToastMessageHandler messageHandler;
public ToastTimer(ToastMessageHandler messageHandler) {
this.messageHandler = messageHandler;
}
#Override
public void run() {
Message message = Message.obtain(messageHandler);
messageHandler.sendMessage(message);
}
}
}
Toast Handler class
public class ToastMessageHandler extends Handler{
Context context;
String message;
public ToastMessageHandler(Context _context , String _message){
this.context = _context;
this.message = _message;
}
#Override
public void handleMessage(Message msg) {
Toast.makeText(msg);
}
}
Related
I would like to update a view from within an open activity when the device receives a push notification.
When a push notification is received the updateBalance function is executed,
a mysql database is queried and an amount is returned.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private void updateBalance(String messageBody) {
h1 = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
bb = msg.getData();
String str = bb.getString("result");
Log.d(TAG,str);
Message msg=handler.obtainMessage()
}
};
t = new Thread(new MyRunnable(h1));
t.start();
try {
t.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I have another class
public class MyRunnable implements Runnable {
private Handler h2;
public MyRunnable(Handler h) {
this.h2 = h;
}
#Override
public void run() {
String name = "w12";
BalanceActivity NB = new BalanceActivity(name);
Message m = Message.obtain();
Bundle b = new Bundle();
b.putString("result", "10");
m.setData(b);
h2.sendMessage(m);
}
}
I have a MainActivity that I would like to update after the amount is returned. How would I do this possibly with another Handler and Runnable.
public class MainActivity extends Activity {
TextView TV = (TextView) findViewById(package.name.R.id.Balance);
}
Try to check your activity is currently in foreground. if yes then create method where you can update your view.
public static boolean isServiceRunning(Context context) {
Log.i(TAG, "Checking if service is running");
ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
boolean isServiceFound = false;
for (int i = 0; i < services.size(); i++) {
if (Constants.PACKAGE.equals(services.get(i).service.getPackageName())){
if (Constants.BACKGROUND_SERVICE_CLASS.equals(services.get(i).service.getClassName())){
isServiceFound = true;
}
}
}
Log.i(TAG, "Service was" + (isServiceFound ? "" : " not") + " running");
return isServiceFound;
}
Make use of Broadcast Receivers. Register local broadcast receiver in activity. Broadcast data when notification received.
I have a dual-sim phone and I need to catch in broadcast receiver at what number the call came (the first or the second)? How to get a phone number?
I did like that, but it works from time to time
public class IncomingCall extends BroadcastReceiver {
#Override public void onReceive(Context context, Intent intent) {
String callingSIM = "";
Bundle bundle = intent.getExtras();
callingSIM =String.valueOf(bundle.getInt("simId", -1));
if(callingSIM == "0"){ }
else if(callingSIM =="1"){ }
}
}
I am using following UsbSerial example from below link https://github.com/felHR85/SerialPortExample. I want receive data from over usb from the device shown in the photo.
Device is basically a counter machine which is sending counter data over serial port.
I am able to connect device and open port from it but unable to read data stream from it. Below is the code used. code is not giving any error
Mainactivity class
public class MainActivity extends AppCompatActivity {
/*
* Notifications from UsbService will be received here.
*/
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;
private 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);
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new MyHandler(this);
display = (TextView) findViewById(R.id.textView1);
editText = (EditText) findViewById(R.id.editText1);
Button sendButton = (Button) findViewById(R.id.buttonSend);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!editText.getText().toString().equals("")) {
String data = editText.getText().toString();
if (usbService != null) { // if UsbService was correctly binded, Send data
display.append(data);
usbService.write(data.getBytes());
}
}
}
});
}
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
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);
}
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);
}
/*
* This handler will be passed to UsbService. Data received from serial port is displayed through this handler
*/
private static class MyHandler extends Handler {
private final WeakReference<MainActivity> mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
mActivity.get().display.append("Handle:");
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
mActivity.get().display.append(data);
break;
}
}
}
}
I know it's bit late, however just to help others who might come across similar issue, did you find solution to your problem? If not, I cannot see the other java file corresponding to the service (USBService.java) as described in the example referred by you. The same file contains following code snippet which you would like to debug to find out what's going wrong (could be a problem with byte to string conversion or so). Hope this helps.
/*
* 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();
}
}
};
I am developing an app that notify the user when any SMS marked as read even if the app isn't running
I simply created a contentobserver and I registered it in a service
the problem is that the contentobserver runs if the new SMS inserted or deleted but when the SMS marked as read ( Update operation) it doesn't work
here is my service code
public class Smssendservice extends Service {
private static Timer timer = new Timer();
private Context ctx;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
ctx = this;
startService();
}
private void startService()
{
//timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
Toast.makeText(getApplicationContext(), "Before Register", Toast.LENGTH_SHORT).show();
final Uri SMS_STATUS_URI = Uri.parse("content://sms");
SMSLogger sl= new SMSLogger();
SMSObserver smsSentObserver = new SMSObserver(sl, ctx);
getContentResolver().registerContentObserver(SMS_STATUS_URI, true, smsSentObserver);
Toast.makeText(getApplicationContext(), "After Register", Toast.LENGTH_SHORT).show();
}
}
I am registering my content observer in the service
here is the content observer code
public class SMSObserver extends ContentObserver
{
SMSLogger smsLogger;
Context context;
public SMSObserver(SMSLogger smsLogger, Context context) {
super(new Handler());
this.context=context;
this.smsLogger = smsLogger;
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
smsLogger.querySMS(context);
}
}
eventually here is the SMS logger that I show the TOAST if the SMS data changed
public class SMSLogger {
protected void querySMS(Context context) {
Uri uriSMS = Uri.parse("content://sms/");
Cursor cur = context.getContentResolver().query(uriSMS, null, null, null, null);
/* cur.moveToNext(); // this will make it point to the first record, which is the last SMS sent
String body = cur.getString(cur.getColumnIndex("body")); //content of sms
String add = cur.getString(cur.getColumnIndex("address")); //phone num
String time = cur.getString(cur.getColumnIndex("date")); //date
String protocol = cur.getString(cur.getColumnIndex("protocol")); //protocol*/
Toast.makeText(context, "Data Changed CHECK SMS" , Toast.LENGTH_SHORT).show();
/*logging action HERE...*/
}
}
it showed this message "Data Changed CHECK SMS" if new SMS inserted or SMS deleted but in case of update the toast doesnt appear. any clue ?
In your update method, check if the number of entries updated is more than 0.
If it is, do getContext().getContentResolver().notifyChange(uri, null); before you return the number of entries updated.
In my app i am using XMPP for chatting, in this i have to create a service to download all the contacts from the XMPP sever to my DataBase. i am doing like below code now, it takes much time to get all contacts, i don't have interest user let to wait to complete download all contacts.
Due to this reason i want to use a service to do this job in background and then store them in DB, i will use provider to update the contacts if database have a new contact.
I know how to create a service but here i am unable to pass parameter like Roster and XMPP connection to service, these parameters are required to download contacts from XMPP server.
please anybody guide me how to solve this problem.
this is the code i am using now.
public class GmailXmppClient {
public GmailXmppClient(ChatAccountsFragment _fragment, Context _context) {
this.fragment = _fragment;
this.context = _context;
ConnectionConfiguration config = new ConnectionConfiguration(server_host, SERVER_PORT, SERVICE_NAME);
m_connection = new XMPPConnection(config);
try {
m_connection.connect();
} catch (XMPPException e) {
e.printStackTrace();
}
}
public Roster getRoster() {
Log.i(TAG, " getRoster ");
return m_connection.getRoster();
}
public boolean Login(String uname, String pass ) throws XMPPException {
m_connection.login(uname, pass);
this.fragment.Gtalk_logInComplete(uname, m_connection);
this.setPacketFilters();
Presence presence = new Presence(Presence.Type.available);
Log.i("ID", "" + presence);
m_connection.sendPacket(presence);
return true;
}
public void disconnect() {
m_connection.disconnect();
}
}
From the above code after this code
this.fragment.Gtalk_logInComplete(uname, m_connection);
this code will run to get contacts from xmpp server
private void getConts() {
Roster roster = colors_xmpp_client.getRoster();
String file_name;
for (RosterEntry entry : roster.getEntries()) {
if (entry.getType() == ItemType.to || entry.getType() == ItemType.both) {
boolean yes = Contact_data_source.checkUsername(entry.getUser());
Log.i(TAG, "Con=" + yes);
if (!yes) {
String na = entry.getUser();
String[] me = na.split("#");
Bitmap buddy_img = buddyImage(entry, _connection);
if (buddy_img != null)
file_name = Store(buddy_img);
else
file_name = "";
if (entry.getName() == null)
Contact_data_source.createContact( entry.getUser(), entry.getUser(), Uname, file_name, UsedStrings.SipAccount, me[0] );
else
Contact_data_source.createContact( entry.getName(), entry.getUser(), Uname, file_name, UsedStrings.SipAccount, me[0] );
} else {
Log.i(TAG, "Con=exist");
}
}
}
return null;
}
You can use the following flow:
1) start Activity, bind RosterService
2) register ContentObserver with desired context (application context, or activity)
context.getContentResolver().registerContentObserver(uriRosterChanged, true, contentObserver);
3) send this context and contentObserver to RosterService
4) in service: get contact and store it into db and !!! >>
5) in service: context.getContentResolver().notifyChange(uriRosterChanged, contentObserver)
6) repeat i.4 for the next contact
i.5 -> will fire contentObserver.onChange method, so here you may refresh your contacts list
How 2 send parameters to service 2 ways described with extras and direct method call (setRosterNConnection()):
Activity code:
...
RosterService mService;
#Override public void onCreate(Bundle savedInstanceState) {
...
Intent intent = new Intent(this, RosterService.class);
intent.putExtra("Key", "Value");
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
...
}
...
Roster mRoster ;
XMPPConnection mConnection;
...
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mService.setRosterNConnection(mRoster, mConnection);
mService.doJob();
}
public void onServiceDisconnected(ComponentName arg0) {
mService = null;
}
};
...
RosterService code:
// some class LocalBinder extends Binder{...} if some needs
private LocalBinder mBinder = new LocalBinder(); // class LocalBinder extends Binder{...}
...
#Override
public IBinder onBind(Intent intent) {
Bundle extras = intent.getExtras();
if(extras == null)
Log.d("RosterService","extras is empty");
else
{
Log.d("RosterService","extras not empty");
String key = (String) extras.get("Key");
...
}
return mBinder;
}
...
public void setRosterNConnection (Roster roster , XMPPConnection connection){
...
}
...
public void doJob(){
// get and save contacts
...
}
Maybe you can do it in a AsyncTask.
AsyncTask just will do the work on another thread, just if user close your activity the asyncTask will be stopped.