I have a handler inside oncreate of an activity. It receives a value from handler.sendEmptyMessage.
handleMessage is fired and it reaches till the line where I try to update the textview as shown below:
mImageCountText.setText("" + mCountText);
But the text of textview never gets changed. What am I missing here?
Is there anything obvious that causes this issue?
Any help is much appreciated.
EDIT
Handler code
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
final int what = msg.what;
if (what == Constants.HANDLER_APP_UPDATE) {
if (!UserHelper.isAppBuildVerionSameAsUpdate(HomeActivity.this)) {
updateNotificationAlert();
showAppUpdatePopUp();
}
} else if (what == Constants.HANDLER_COLLECTION_UPDATE) {
//TODO: Refresh collection
} else {
mCountText = what;
if (!Utils.isTablet()) {
if (mCountText == 0) {
mImageCountText.setVisibility(View.INVISIBLE);
} else {
mImageCountText.setVisibility(View.VISIBLE);
mImageCountText.setText("" + mCountText); // this does not work
}
} else {
if (mCountText == 0) {
mCollectionsFragment.refreshAfterUpload();
mCountTextForUplaod.setVisibility(View.INVISIBLE);
} else {
mCollectionsFragment.refreshAfterUpload();
mCountTextForUplaod.setVisibility(View.VISIBLE);
mCountTextForUplaod.setText("" + mCountText);
}
}
}
}
};
Onreceive from where value is sent
#Override
public void onReceive(final Context context, final Intent intent) {
Runnable runnable = new Runnable() {
public void run() {
if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_INTENT_FILTER)) {
boolean broadcastStatus = intent.getBooleanExtra(Constants.BROADCAST_DATA_STATUS, false);
String broadcastStatusMessage = intent.getStringExtra(Constants.BROADCAST_DATA_STATUS_MESAGE);
if (broadcastStatus) {
mCountText = PreferenceHelper.getFromPreference(context, Constants.RECENT_IMAGES_COUNT, 0);
handler.sendEmptyMessage(PreferenceHelper.getFromPreference(context, Constants.RECENT_IMAGES_COUNT, 0));
}
} else {
if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_ACTION_APP_UPDATE)) {
handler.sendEmptyMessage(Constants.HANDLER_APP_UPDATE);
} else if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_ACTION_COLLECTION_UPDATE)) {
handler.sendEmptyMessage(Constants.HANDLER_COLLECTION_UPDATE);
}
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
Your code is too complex. You don't need the handler and definitively not the thread. Thy it like this:
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_INTENT_FILTER)) {
boolean broadcastStatus = intent.getBooleanExtra(Constants.BROADCAST_DATA_STATUS, false);
String broadcastStatusMessage = intent.getStringExtra(Constants.BROADCAST_DATA_STATUS_MESAGE);
if (broadcastStatus) {
mCountText = PreferenceHelper.getFromPreference(context, Constants.RECENT_IMAGES_COUNT, 0);
if (mCountText == 0) {
mCollectionsFragment.refreshAfterUpload();
mCountTextForUplaod.setVisibility(View.INVISIBLE);
} else {
mCollectionsFragment.refreshAfterUpload();
mCountTextForUplaod.setVisibility(View.VISIBLE);
mCountTextForUplaod.setText("" + mCountText);
}
}
} else {
if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_ACTION_APP_UPDATE)) {
if (!UserHelper.isAppBuildVerionSameAsUpdate(HomeActivity.this)) {
updateNotificationAlert();
showAppUpdatePopUp();
}
} else if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_ACTION_COLLECTION_UPDATE)) {
// TODO
}
}
}
Related
I am making a default phone call. Everything works well till I made a call to the switchboard operator.
In this kind of call, the phone says: "Press 1 to do A, press 2 to do B".
I did some research for hours but couldn't find one...
I did try this code, but it doesn't work.
keyPressed(KeyEvent.KEYCODE_1); // when press key 1
private void keyPressed(int keyCode) {
....
Intent i = new Intent(Intent.ACTION_CALL, Uri.parse("tel://" + keyCode));
startActivity(I);
....
playTone(ToneGenerator.TONE_DTMF_1, TONE_LENGTH_INFINITE);
}
Big thanks for any of your suggestions!
Added 1:
I am using InCallService like this:
class CallService : InCallService() {
private var isShowEnded = true
override fun onCallAdded(call: Call) {
super.onCallAdded(call)
OngoingCall().setCall(call)
CallActivity.getInstance().start(this, call)
isShowEnded = false
}
override fun onCallRemoved(call: Call) {
super.onCallRemoved(call)
OngoingCall().setCall(null)
}
}
and OngoingCall:
public class OngoingCall {
public static BehaviorSubject<Integer> state = BehaviorSubject.create();
private static Call sCall;
public Call getsCall() {
return sCall;
}
#RequiresApi(api = Build.VERSION_CODES.M)
private Object callback = new Call.Callback() {
#Override
public void onStateChanged(Call call, int newState) {
super.onStateChanged(call, newState);
state.onNext(newState);
}
};
#RequiresApi(api = Build.VERSION_CODES.M)
public final void setCall(#Nullable Call value) {
if (sCall != null) {
sCall.unregisterCallback((Call.Callback) callback);
}
if (value != null) {
value.registerCallback((Call.Callback) callback);
state.onNext(value.getState());
}
sCall = value;
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void answer() {
if (sCall != null) {
assert sCall != null;
sCall.answer(VideoProfile.STATE_AUDIO_ONLY);
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void hold(boolean hold) {
if (sCall != null) {
if (hold) sCall.hold();
else sCall.unhold();
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void addCall(Call call) {
if (sCall != null) {
sCall.conference(call);
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void hangup() {
if (sCall != null) {
sCall.disconnect();
}
}
}
And then I tried this when pressing keyboard:
mTrueCallerOngoingCall.getsCall().playDtmfTone((char) tone); // inside playTone()
But it's still not working :(
Update 2:
I have fixed my adding this method:
private char getChar(int tone) {
if (tone == 0) return '0';
else if (tone == 1) return '1';
else if (tone == 2) return '2';
else if (tone == 3) return '3';
else if (tone == 4) return '4';
else if (tone == 5) return '5';
else if (tone == 6) return '6';
else if (tone == 7) return '7';
else if (tone == 8) return '8';
else if (tone == 9) return '9';
else if (tone == 10) return '*';
else return '#';
}
and change from my above code to
mTrueCallerOngoingCall.getsCall().playDtmfTone(getChar(tone));
mTrueCallerOngoingCall.getsCall().stopDtmfTone();
It is .Hope can help you.
call.playDtmfTone(char);
The call PATH:
android.telecom.Call;
From: Any Class extends InCallService.
In Method: onCallAdded(call);
Sometime I am facing this issue my intent service crash while I restart it again on onReceive() method.
Here is my stack trace.
"java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ComponentName android.content.Intent.getComponent()' on a null object reference
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1207)
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1238)
at android.app.ContextImpl.startService(ContextImpl.java:1222)
at android.content.ContextWrapper.startService(ContextWrapper.java:581)
at com.live.wheelz.MapFragmentPassenger$ResponseReceiver$3.run(MapFragmentPassenger.java:3162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
"
Here is my code
public class ResponseReceiver extends WakefulBroadcastReceiver {
public static final String ACTION_RESP = "com.live.ResponseReceiver.intent.action.MESSAGE_PROCESSED";
#Override
public void onReceive(Context context, Intent intent) {
if(!intent.getStringExtra("journeyState").equals("jr_droped") && !intent.getStringExtra("journeyState").equals("jr_canceled") ) {
if(intent.getStringExtra("journeyState").equals("jr_arrived") && alertCounter==0) {
alertCounter=alertCounter+1;
popUp.dismisDialog();
soundAlert.initRigtone("Driver is arrived at your location");
// snack("Driver is arrived at your location","message","long");
}
if (sharedData.getisSimulation() == true) {
if (intent.getBooleanExtra("same", true) == false) {
double latc = intent.getDoubleExtra("pDriverLatitude", 0.0);
double lonc = intent.getDoubleExtra("pDriverLongitude", 0.0);
//dname.setText("Latitude:"+lat+"Longitude:"+lon);
if (driver != null) {
driver.remove();
}
//String address=getaddress(latpickup,lonpickup);
for (Marker oc : nearest_driver) {
oc.remove();
}
driver = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latc, lonc))
.title("Current location Driver").icon(BitmapDescriptorFactory.fromResource(R.drawable.bike_left))
.draggable(true));
if (markerlocation != null) {
markerlocation.remove();
}
markerlocation = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(sharedData.getnewlat(), sharedData.getnewlon()))
.title("Passenger Current Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.bluedot)));
if (sharedData.getisRating() == false) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
startService(servicedriver);
}
catch (Exception ex)
{
System.out.print("");
}
}
}, sharedData.getPassenger_request_delay_time());
}
}
if (intent.getBooleanExtra("same", false) == true) {
if (markerlocation != null) {
markerlocation.remove();
}
markerlocation = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(sharedData.getnewlat(), sharedData.getnewlon()))
.title("Passenger Current Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.bluedot)));
if (sharedData.getisRating() == false) {
if (receiver != null) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
startService(servicedriver);
}
catch (Exception ex)
{
System.out.print("");
}
//startService(servicedriver);
}
}, sharedData.getPassenger_request_delay_time());
}
}
}
}
if (sharedData.getisSimulation() == false) {
if (intent.getBooleanExtra("same", false) == false) {
if (intent.getBooleanExtra("connection_error", false) == false) {
latc = intent.getDoubleExtra("pDriverLatitude", 0.0);
lonc = intent.getDoubleExtra("pDriverLongitude", 0.0);
//snack("Driver Current lat:"+latc+" Driver Current lon:"+lonc, "message", " ");
//Ali Abbas Location Diffrnce Calc
double latDrvr = sharedData.getPickuplocationlat();
double lonDrvr = sharedData.getPickuplocationlon();
double distanceDiff = getDistanceInMiles(latc,lonc,latDrvr,lonDrvr);
double getDisrnce = sharedata.getDrvrPsngrRnge() ;
if(distanceDiff <= sharedata.getDrvrPsngrRnge() && intent.getStringExtra("journeyState").equals("jr_driverAccepted")) {
/*if (!ISPOPUPED) {
ISPOPUPED =true ;*/
fncDrvrArndPsngr();
//}
}else if(distanceDiff > sharedata.getDrvrPsngrRnge() && intent.getStringExtra("journeyState").equals("jr_driverAccepted")){
fncDrvrArndPsngrPopUpDismiss();
}
//Ali Abbas Distance Calc Ends
}
smoothly(latc, lonc);
if (sharedData.getisRating() == false) {
if (intent.getBooleanExtra("connection_error", true) == true) {
snack("Internet Connection Error", "message", " ");
fncDrvrArndPsngrPopUpDismiss();
} else {
AppAsynTaskAddress setaddress = new AppAsynTaskAddress(MapFragmentPassenger.this, latc, lonc, "driverlocation", false);
setaddress.execute();
//snack("Driver Arrived at:"+pickuplocationtext.getText().toString(), "message", " ");
}
if (receiver != null) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
startService(servicedriver);
}
catch (Exception ex)
{
System.out.print("");
}
//startService(servicedriver);
}
}, sharedData.getPassenger_request_delay_time());//sharedData.getPassenger_request_delay_time()
}
} else {
googleMap.clear();
}
}
if (intent.getBooleanExtra("same", true) == true) {
if (sharedData.getisRating() == false) {
//snack("Same lat lon", "message", " ");
if (receiver != null) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
startService(servicedriver);
}
catch (Exception ex)
{
System.out.print("");
}
// startService(servicedriver);
}
}, sharedData.getPassenger_request_delay_time());//sharedData.getPassenger_request_delay_time()
}
} else {
googleMap.clear();
}
}
}
}
if(intent.getStringExtra("journeyState").equals("jr_droped")) {
if(!sharedata.isOnRatingScreen()) {
Intent intSetPass = new Intent(MapFragmentPassenger.this, Ratingscreenpassenger.class);
intSetPass.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intSetPass);
}
}
if(intent.getStringExtra("journeyState").equals("jr_canceled")) {
sharedata.setJmode(false);
sharedata.setisRating(true);
//db.deleteBillingParameter();
db.deleteJourneyRating(sharedata.getDriver_rquested_journeyid(), "p");
changebutton();
snack("Journey Canceled","message","long");
soundAlert.initRigtone("Journey Canceled");
}
}
}
I solve it after doing some debugging startService(servicedriver); servicedriver object is null I start it again if it is null like
if(servicedriver!=null) {
startService(servicedriver);
}
else{
startservice();
}
here is start service
public void startservice() {
if (sharedData.getisSimulation() == true) {
jmode = true;
sharedData.setisRating(false);
servicedriver = new Intent(this, LocationService.class);
this.startService(servicedriver);
sharedData.setJmode(true);
}
if (sharedData.getisSimulation() == false) {
jmode = true;
sharedData.setisRating(false);
servicedriver = new Intent(this, LocationServiceDriver.class);
this.startService(servicedriver);
sharedData.setJmode(true);
}
}
I'm writinng Android app that receiving data via bluetooth from another device. Those data as in fact streaming non-stop. After getting about 50 or 70 of them, app slows down and stop showing me received data. App cache is full, but clearing it (deleting context.getCacheDir()) doesn't help. After restarting whole app, I can again get next part of data. WHat can I do for avoiding this "lag"?
my MainActivity:
public class MainActivity extends Activity {
private BluetoothAdapter bluetoothAdapter;
private boolean pendingRequestEnableBt = false;
private final String SAVED_PENDING_REQUEST_ENABLE_BT = "PENDING_REQUEST_ENABLE_BT";
private BluetoothResponseHandler mHandler;
private static MainActivity instance;
private DeviceConnector connector;
private TextView console;
private String deviceName;
private final int REQUEST_CONNECT_DEVICE = 1;
private final int REQUEST_ENABLE_BT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
instance = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
console = (TextView) findViewById(R.id.main_text_console);
if (savedInstanceState != null) {
pendingRequestEnableBt = savedInstanceState.getBoolean(SAVED_PENDING_REQUEST_ENABLE_BT);
}
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "No bluetooth available", Toast.LENGTH_LONG).show();
}
if (mHandler == null) {
mHandler = new BluetoothResponseHandler(this);
} else {
mHandler.setTarget(this);
}
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
getActionBar().setSubtitle(deviceName);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_PENDING_REQUEST_ENABLE_BT, pendingRequestEnableBt);
outState.putString("device_name", deviceName);
if (console != null) {
final String log = console.getText().toString();
outState.putString("AC", log);
}
}
public boolean isAdapterReady() {
return (bluetoothAdapter != null) && (bluetoothAdapter.isEnabled());
}
private static class BluetoothResponseHandler extends Handler {
private WeakReference<MainActivity> mActivity;
public BluetoothResponseHandler(MainActivity activity) {
mActivity = new WeakReference<MainActivity>(activity);
}
public void setTarget(MainActivity target) {
mActivity.clear();
mActivity = new WeakReference<MainActivity>(target);
}
#Override
public void handleMessage(Message msg) {
MainActivity activity = mActivity.get();
if (activity != null) {
if (msg.what==MessageType.MESSAGE_STATE_CHANGE.getValue()) {
final ActionBar bar = activity.getActionBar();
switch (msg.arg1) {
case DeviceConnector.STATE_CONNECTED:
bar.setSubtitle("Połączono.");
break;
case DeviceConnector.STATE_CONNECTING:
bar.setSubtitle("Łączenie");
break;
case DeviceConnector.STATE_NONE:
bar.setSubtitle("Rozłączono.");
break;
}
} else if (msg.what==MessageType.MESSAGE_READ.getValue()) {
if (msg.obj != null) {
activity.appendLog((String)msg.obj);
}
} else if (msg.what==MessageType.MESSAGE_DEVICE_NAME.getValue()) {
activity.setDeviceName((String) msg.obj);
}
}
}
}
private void startDeviceListActivity() {
stopConnection();
startActivityForResult(new Intent(this, DeviceListActivity.class), REQUEST_CONNECT_DEVICE);
}
private void stopConnection() {
if (connector != null) {
connector.stop();
connector = null;
}
}
#Override
public boolean onSearchRequested() {
if (isAdapterReady()) {
startDeviceListActivity();
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.device_control_activity, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
if (isAdapterReady() && (connector == null)) setupConnector(device);
}
break;
case REQUEST_ENABLE_BT:
pendingRequestEnableBt = false;
if (resultCode != Activity.RESULT_OK) {
Toast.makeText(this, "Bt not enabled", Toast.LENGTH_LONG).show();
}
break;
}
}
private void setupConnector(BluetoothDevice connectedDevice) {
stopConnection();
connector = new DeviceConnector(new DeviceData(connectedDevice, getString(R.string.empty_device_name)), mHandler);
connector.connect();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
if (isAdapterReady()) {
if (isConnected()) {
stopConnection();
} else {
startDeviceListActivity();
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void appendLog(String message) {
String msg = message.replaceAll("[\n\t\r ]*", "");
console.append(msg.length() + ": " + msg + "\n");
final int scrollAmount = console.getLayout().getLineTop(console.getLineCount()) - console.getHeight();
console.scrollTo(0, scrollAmount>0?scrollAmount:0);
delete(getCacheDir());
}
private boolean isConnected() {
return (connector != null) && (connector.getState() == DeviceConnector.STATE_CONNECTED);
}
public static MainActivity getInstance() {
return instance;
}
public void delete(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
for (File f:file.listFiles()) {
delete(f);
}
}
}
}
}
this code is downloaded, it isn't mine, I just modified it.
To update a seekbar, I am using the following code:
My problem is that anytime the seekBar.setProgress() is call, other element on the UI become freezed, so I would like to have a different thread that update the seekBar in the main thread.
How to proceed ?
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
try {
int pos;
switch (msg.what) {
case SHOW_PROGRESS:
pos = setProgress();
if (!mDragging && mBoundService.isPlaying()) {
msg = obtainMessage(SHOW_PROGRESS);
sendMessageDelayed(msg, 100 - (pos % 1000));
}
break;
}
} catch (Exception e) {
}
}
};
private int setProgress() {
if (mBoundService == null || mDragging) {
return 0;
}
int position = mBoundService.getCurrentPosition();
int duration = mBoundService.getDuration();
if (sliderSeekBar != null) {
if (duration > 0) {
// use long to avoid overflow
long pos = 1000L * position / duration;
sliderSeekBar.setProgress((int) pos);
}
}
if (sliderTimerStop != null)
sliderTimerStop.setText(stringForTime(duration));
if (sliderTimerStart != null)
sliderTimerStart.setText(stringForTime(position));
return position;
}
Activities have a runOnUiThread method that allows separate threads to update UI components. Your setProgress method would end up looking like:
private int setProgress() {
if (mBoundService == null || mDragging) {
return 0;
}
final int position = mBoundService.getCurrentPosition();
final int duration = mBoundService.getDuration();
runOnUiThread(new Runnable(){
#Override
public void run(){
if (sliderSeekBar != null) {
if (duration > 0) {
// use long to avoid overflow
long pos = 1000L * position / duration;
sliderSeekBar.setProgress((int) pos);
}
}
if (sliderTimerStop != null)
sliderTimerStop.setText(stringForTime(duration));
if (sliderTimerStart != null)
sliderTimerStart.setText(stringForTime(position));
}
});
return position;
}
This is a bit weird, but I have no idea where the problem is.
In my onCreate() I have this code:
GameRunningNotesTimer().start();
and then out of onCreate I have this code:
Thread GameRunningNotesTimer = new Thread(new Runnable() {
public void run() {
int sleepingTime;
try {
if (r_settings.getGameOver() == 0) {
sleepingTime = 1000 - (r_settings.getInternalLevel() * 100);
if (r_settings.getInternalLevel() == 0) {
Thread.sleep(1000);
} else {
if (sleepingTime <= 399)
{
sleepingTime = 350;
}
Thread.sleep(sleepingTime);
}
if (r_settings.getGameOver() == 1){ gameOver(); }
myHandler2.sendEmptyMessage(0);
} // End of if (r_settings.getGameOver()
} catch (Exception e) { Log.e("MUSIC!!!!!", "Error in activity", e); }
}// End of run
}); // End of GameRunningNotesTimer()
final Handler myHandler2 = new Handler() {
#Override
public void handleMessage(Message msg) {
//text2.setText(""+item[0]);
int z = 1;
if (r_settings.getGameStarted() == true)
{
changeNoteFromTimer();
} else {
startingCountdown(z);
}
} // end of handleMessage()
};
but this GameRunningNotesTimer().start(); is underlined in red (in Eclipse) and when I mouseover it it says: The method GameRunningNotesTimer() is undefined for the type GameScr
What am I doing wrong? another thread/handler in the same class is not giving me this problem.
Thanks!
It should be GameRunningNotesTimer.start(); not GameRunningNotesTimer().start();