Run the tasks in background ( AsyncTask ) - android

In NoteInfoactivity I have a code below, but
Note allNote = NoteDatabase.getInstance(getApplicationContext()).noteDao().getAllNoteId(noteID);
is executed in main thread. How can i execute it in background? what is the best way?
public class NoteInfoActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_info);
TextView textViewTitle = findViewById(R.id.textViewNoteTitle);
TextView textViewPriority = findViewById(R.id.textViewPriority);
Intent intent = getIntent();
if (intent != null && intent.hasExtra("NoteID")) {
long noteID = intent.getIntExtra("NoteID", -1);
Note allNote = NoteDatabase.getInstance(getApplicationContext()).noteDao().getAllNoteId(noteID);
String title = allNote.getTitle();
int priority = allNote.getPriority();
textViewTitle.setText(title);
textViewPriority.setText(String.valueOf(priority));
} else {
Toast.makeText(getApplicationContext(), R.string.empty_not_saved, Toast.LENGTH_SHORT).show();
}
}
}

You can put it in a thread and then call for a handler to do the UI changes on the main thread.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_info);
TextView textViewTitle = findViewById(R.id.textViewNoteTitle);
TextView textViewPriority = findViewById(R.id.textViewPriority);
Intent intent = getIntent();
Handler handler = new Handler();
if (intent != null && intent.hasExtra("NoteID")) {
long noteID = intent.getIntExtra("NoteID", -1);
new Thread(new Runnable() {
#Override
public void run() {
Note allNote = NoteDatabase.getInstance(getApplicationContext()).noteDao().getAllNoteId(noteID);
handler.post((Runnable) () -> {
String title = allNote.getTitle();
int priority = allNote.getPriority();
textViewTitle.setText(title);
textViewPriority.setText(String.valueOf(priority));
});
}
}).start();
} else {
Toast.makeText(getApplicationContext(), R.string.empty_not_saved, Toast.LENGTH_SHORT).show();
}
}

Related

Switch state using intent [duplicate]

I was in trouble with logical error somewhere in my program, what happening is when I use time picker and Switch in my MainActivity then the time selected and Switch state getting changed in my another activity i.e: UtilMainActivity which is a subclass. But whereas, when I change the switch state and time in my UtilMainActivity it is not resulting in a change of switch state and alarm time in my MainActivity.What I actually need is when I change alarm time and switch in MainActivity does not lead to change of time and switch in my UtilMainActivity.......Hope You understand my problem. Here is My MainActivity.
UtilMainActivity
public class UtilMainActivity extends AppCompatActivity implements
TimePickerDialog.OnTimeSetListener {
SwitchCompat onOffSwitch;
TextView firstAlarmTextView;
TextView timeLeftTextView;
LinearLayout firstAlarmLayout;
UtilSharedPreferencesHelper sharPrefHelper;
UtilTimerManager utilTimerManager;
UtilAlarmParams utilAlarmParams;
BroadcastReceiver timeLeftReceiver;
private final String LOG_TAG = UtilMainActivity.class.getSimpleName();
final int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 45;
final float DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION = 2f; // number of alarms, first alarm, interval values text size is larger than text around them
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.utility_activity_main);
onOffSwitch = (SwitchCompat) findViewById(R.id.switch_main);
firstAlarmLayout = (LinearLayout) findViewById(R.id.layout_main_firstalarm);
firstAlarmTextView = (TextView) findViewById(R.id.textview_main_firstalarm_time);
timeLeftTextView = (TextView) findViewById(R.id.textview_main_timeleft);
sharPrefHelper = new UtilSharedPreferencesHelper(UtilMainActivity.this);
sharPrefHelper.printAll();
utilAlarmParams = sharPrefHelper.utilgetParams();
utilTimerManager = new UtilTimerManager(UtilMainActivity.this);
showFirstAlarmTime(utilAlarmParams.firstUtilAlarmTime.toString());
showTimeLeft(utilAlarmParams);
onOffSwitch.setChecked(sharPrefHelper.isAlarmTurnedOn());
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
utilAlarmParams.turnedOn = isChecked;
if (isChecked) {
checkNotificationPolicy();
checkOverlayPermission();
utilTimerManager.startSingleAlarmTimer(utilAlarmParams.firstUtilAlarmTime.toMillis());
showToast(getString(R.string.utility_main_alarm_turned_on_toast));
} else {
utilTimerManager.cancelTimer();
showToast(getString(R.string.utility_main_alarm_turned_off_toast));
}
showTimeLeft(utilAlarmParams);
sharPrefHelper.utilsetAlarmState(isChecked);
}
});
firstAlarmLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle timePickerBundle = new Bundle();
timePickerBundle.putInt(UtilTimePickerDialogFragment.BUNDLE_KEY_ALARM_HOUR, sharPrefHelper.utilgetHour());
timePickerBundle.putInt(UtilTimePickerDialogFragment.BUNDLE_KEY_ALARM_MINUTE, sharPrefHelper.utilgetMinute());
UtilTimePickerDialogFragment timePicker = new UtilTimePickerDialogFragment();
timePicker.setArguments(timePickerBundle);
timePicker.show(getFragmentManager(), UtilTimePickerDialogFragment.FRAGMENT_TAG);
}
});
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onResume() {
super.onResume();
showTimeLeft(utilAlarmParams);
timeLeftReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0) { //i.e. every minute
showTimeLeft(utilAlarmParams);
}
}
};
registerReceiver(timeLeftReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
#Override
protected void onPause() {
super.onPause();
if (timeLeftReceiver != null) {
unregisterReceiver(timeLeftReceiver);
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
UtilAlarmTime utilAlarmTime = new UtilAlarmTime(hour, minute);
utilAlarmParams.firstUtilAlarmTime = utilAlarmTime;
showFirstAlarmTime(utilAlarmTime.toString());
showTimeLeft(utilAlarmParams);
resetTimerIfTurnedOn();
sharPrefHelper.utilsetTime(utilAlarmTime);
}
private void showToast(String message) {
Toast.makeText(UtilMainActivity.this, message, Toast.LENGTH_SHORT).show();
}
private void resetTimerIfTurnedOn() {
if (onOffSwitch.isChecked()) {
utilTimerManager.resetSingleAlarmTimer(utilAlarmParams.firstUtilAlarmTime.toMillis());
showToast(getString(R.string.utility_main_alarm_reset_toast));
}
}
private void showFirstAlarmTime(String firstAlarmTime) {
String wholeTitle = getString(R.string.utility_main_firstalarm_time, firstAlarmTime);
SpannableString wholeTitleSpan = new SpannableString(wholeTitle);
wholeTitleSpan.setSpan(new RelativeSizeSpan(DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION),
wholeTitle.indexOf(firstAlarmTime) - 1,
wholeTitle.indexOf(firstAlarmTime) + firstAlarmTime.length(), 0);
firstAlarmTextView.setText(wholeTitleSpan);
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void showTimeLeft(UtilAlarmParams utilAlarmParams) {
UtilAlarmTime utilAlarmTime = utilAlarmParams.firstUtilAlarmTime;
timeLeftTextView.setText(getString(R.string.utility_all_time_left, utilAlarmTime.getHoursLeft(), utilAlarmTime.getMinutesLeft()));
if (utilAlarmParams.turnedOn) {
timeLeftTextView.setTextColor(getColor(R.color.primary));
} else {
timeLeftTextView.setTextColor(getColor(R.color.main_disabled_textcolor));
}
Log.d(LOG_TAG, "Time left: "+ utilAlarmTime.getHoursLeft() + ":" + utilAlarmTime.getMinutesLeft());
}
private void checkNotificationPolicy() {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !notificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(
android.provider.Settings
.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
}
/**
* needed for Android Q: on some devices activity doesn't show from fullScreenNotification without
* permission SYSTEM_ALERT_WINDOW
*/
#RequiresApi(api = Build.VERSION_CODES.M)
private void checkOverlayPermission() {
if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.P) && (!Settings.canDrawOverlays(this))) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements
IntervalDialogFragment.IntervalDialogListener,
NumberOfAlarmsDialogFragment.NumberOfAlarmsDialogListener,
TimePickerDialog.OnTimeSetListener {
SwitchCompat onOffSwitch;
ListView alarmsListView;
TextView intervalBetweenAlarmsTextView;
TextView numberOfAlarmsTextView;
TextView firstAlarmTextView;
TextView timeLeftTextView;
LinearLayout firstAlarmLayout;
LinearLayout intervalLayout;
LinearLayout numberOfAlarmsLayout;
AlarmsListHelper alarmsListHelper;
SharedPreferencesHelper sharPrefHelper;
TimerManager timerManager;
AlarmParams alarmParams;
BroadcastReceiver timeLeftReceiver;
Button sleepTimer;
private final String LOG_TAG = MainActivity.class.getSimpleName();
final int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 45;
final float DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION = 2f; // number of alarms, first alarm, interval values text size is larger than text around them
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmsListView = (ListView) findViewById(R.id.listview_main_alarmslist);
onOffSwitch = (SwitchCompat) findViewById(R.id.util_switch_main);
intervalBetweenAlarmsTextView = (TextView) findViewById(R.id.textview_main_interval);
numberOfAlarmsTextView = (TextView) findViewById(R.id.textview_main_numberofalarms);
firstAlarmLayout = (LinearLayout) findViewById(R.id.layout_main_firstalarm);
firstAlarmTextView = (TextView) findViewById(R.id.util_textview_main_firstalarm_time);
timeLeftTextView = (TextView) findViewById(R.id.textview_main_timeleft);
intervalLayout = (LinearLayout) findViewById(R.id.layout_main_interval);
numberOfAlarmsLayout = (LinearLayout) findViewById(R.id.layout_main_numberofalarms);
sleepTimer = (Button) findViewById(R.id.sleepTimer);
sharPrefHelper = new SharedPreferencesHelper(MainActivity.this);
sharPrefHelper.printAll();
alarmParams = sharPrefHelper.getParams();
timerManager = new TimerManager(MainActivity.this);
alarmsListHelper = new AlarmsListHelper(MainActivity.this, alarmsListView);
showFirstAlarmTime(alarmParams.firstAlarmTime.toString());
showTimeLeft(alarmParams);
showInterval(sharPrefHelper.getIntervalStr());
showNumberOfAlarms(sharPrefHelper.getNumberOfAlarmsStr());
onOffSwitch.setChecked(sharPrefHelper.isAlarmTurnedOn());
alarmsListHelper.showList(alarmParams);
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
alarmParams.turnedOn = isChecked;
if (isChecked) {
checkNotificationPolicy();
checkOverlayPermission();
timerManager.startSingleAlarmTimer(alarmParams.firstAlarmTime.toMillis());
showToast(getString(R.string.main_alarm_turned_on_toast));
sharPrefHelper.setNumberOfAlreadyRangAlarms(0);
} else {
timerManager.cancelTimer();
showToast(getString(R.string.main_alarm_turned_off_toast));
}
alarmsListHelper.showList(alarmParams);
showTimeLeft(alarmParams);
sharPrefHelper.setAlarmState(isChecked);
}
});
intervalLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntervalDialogFragment dialog = new IntervalDialogFragment();
Bundle intervalBundle = new Bundle();
intervalBundle.putString(IntervalDialogFragment.BUNDLE_KEY_INTERVAL, sharPrefHelper.getIntervalStr());
dialog.setArguments(intervalBundle);
dialog.show(getFragmentManager(), IntervalDialogFragment.FRAGMENT_TAG);
}
});
numberOfAlarmsLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NumberOfAlarmsDialogFragment dialog = new NumberOfAlarmsDialogFragment();
Bundle numberOfAlarmsBundle = new Bundle();
numberOfAlarmsBundle.putString(NumberOfAlarmsDialogFragment.BUNDLE_KEY_NUMBER_OF_ALARMS, sharPrefHelper.getNumberOfAlarmsStr());
dialog.setArguments(numberOfAlarmsBundle);
dialog.show(getFragmentManager(), NumberOfAlarmsDialogFragment.FRAGMENT_TAG);
}
});
firstAlarmLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle timePickerBundle = new Bundle();
timePickerBundle.putInt(TimePickerDialogFragment.BUNDLE_KEY_ALARM_HOUR, sharPrefHelper.getHour());
timePickerBundle.putInt(TimePickerDialogFragment.BUNDLE_KEY_ALARM_MINUTE, sharPrefHelper.getMinute());
TimePickerDialogFragment timePicker = new TimePickerDialogFragment();
timePicker.setArguments(timePickerBundle);
timePicker.show(getFragmentManager(), TimePickerDialogFragment.FRAGMENT_TAG);
}
});
sleepTimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openNewActivity();
}
});
}
public void openNewActivity(){
Intent intent = new Intent(this, SleepTimerActivity.class);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
showTimeLeft(alarmParams);
timeLeftReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0) { //i.e. every minute
showTimeLeft(alarmParams);
}
}
};
registerReceiver(timeLeftReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
#Override
protected void onPause() {
super.onPause();
if (timeLeftReceiver != null) {
unregisterReceiver(timeLeftReceiver);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
new Handler().post(new Runnable() {
#Override
public void run() {
final View view = findViewById(R.id.scheduleactivity);
if (view != null) {
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Do something...
Toast.makeText(getApplicationContext(), "Scheduled Utilities Stopper", Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings: {
Intent intent = new Intent(this, PrefActivity.class);
startActivity(intent);
break;
}
case R.id.scheduleactivity: {
Intent intent = new Intent(this, UtilMainActivity.class);
startActivity(intent);
break;
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onIntervalChanged(String intervalStr) {
showInterval(intervalStr);
alarmParams.interval = Integer.parseInt(intervalStr);
alarmsListHelper.showList(alarmParams);
resetTimerIfTurnedOn();
sharPrefHelper.setInterval(intervalStr);
}
#Override
public void onNumberOfAlarmsChanged(String numberOfAlarmsStr) {
showNumberOfAlarms(numberOfAlarmsStr);
alarmParams.numberOfAlarms = Integer.parseInt(numberOfAlarmsStr);
alarmsListHelper.showList(alarmParams);
resetTimerIfTurnedOn();
sharPrefHelper.setNumberOfAlarms(numberOfAlarmsStr);
}
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
AlarmTime alarmTime = new AlarmTime(hour, minute);
alarmParams.firstAlarmTime = alarmTime;
showFirstAlarmTime(alarmTime.toString());
alarmsListHelper.showList(alarmParams);
showTimeLeft(alarmParams);
sharPrefHelper.setNumberOfAlreadyRangAlarms(0);
resetTimerIfTurnedOn();
sharPrefHelper.setTime(alarmTime);
}
private void showToast(String message) {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
private void resetTimerIfTurnedOn() {
if (onOffSwitch.isChecked()) {
timerManager.resetSingleAlarmTimer(alarmParams.firstAlarmTime.toMillis());
showToast(getString(R.string.main_alarm_reset_toast));
}
}
private void showInterval(String interval) {
String wholeTitle = getString(R.string.main_interval, interval);
SpannableString wholeTitleSpan = new SpannableString(wholeTitle);
wholeTitleSpan.setSpan(new RelativeSizeSpan(DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION), wholeTitle.indexOf(interval), interval.length() + 1, 0);
intervalBetweenAlarmsTextView.setText(wholeTitleSpan);
}
private void showNumberOfAlarms(String numberOfAlarms) {
int numberOfAlarmsInt = Integer.parseInt(numberOfAlarms);
String wholeTitle = this.getResources().getQuantityString(R.plurals.main_number_of_alarms, numberOfAlarmsInt, numberOfAlarmsInt);
SpannableString wholeTitleSpan = new SpannableString(wholeTitle);
wholeTitleSpan.setSpan(new RelativeSizeSpan(DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION),
wholeTitle.indexOf(numberOfAlarms),
numberOfAlarms.length() + 1, 0);
numberOfAlarmsTextView.setText(wholeTitleSpan);
}
private void showFirstAlarmTime(String firstAlarmTime) {
String wholeTitle = getString(R.string.main_firstalarm_time, firstAlarmTime);
SpannableString wholeTitleSpan = new SpannableString(wholeTitle);
wholeTitleSpan.setSpan(new RelativeSizeSpan(DISPLAYED_NUMBERS_SIZE_RELATIVE_TO_TEXT_PROPORTION),
wholeTitle.indexOf(firstAlarmTime) - 1,
wholeTitle.indexOf(firstAlarmTime) + firstAlarmTime.length(), 0);
firstAlarmTextView.setText(wholeTitleSpan);
}
private void showTimeLeft(AlarmParams alarmParams) {
AlarmTime alarmTime = alarmParams.firstAlarmTime;
timeLeftTextView.setText(getString(R.string.all_time_left, alarmTime.getHoursLeft(), alarmTime.getMinutesLeft()));
if (alarmParams.turnedOn) {
timeLeftTextView.setTextColor(getColor(R.color.primary));
} else {
timeLeftTextView.setTextColor(getColor(R.color.main_disabled_textcolor));
}
Log.d(LOG_TAG, "Time left: "+alarmTime.getHoursLeft() + ":" + alarmTime.getMinutesLeft());
}
private void checkNotificationPolicy() {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !notificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(
android.provider.Settings
.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
}
/**
* needed for Android Q: on some devices activity doesn't show from fullScreenNotification without
* permission SYSTEM_ALERT_WINDOW
*/
private void checkOverlayPermission() {
if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.P) && (!Settings.canDrawOverlays(this))) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
}
}
Your activity, won't get the new data, because it's receiver was already unregistered, to make this easier for you, I would advise, you start the activity with startActivityForResult that way when you are done, you can set the data and the previous activity will receive the data in a bundle on this callback onActivityResult(...)

android picasso doesn't work when application start

I am using picasso with timer to change url of image in MainActivity oncreate() so first time i open application it doesn't work i navigate to other activity and return to main it works
i am printing 'test' in Runnable and it is working
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parent_view = findViewById(android.R.id.content);
Image_view = findViewById(R.id.adv_image);
global = (GlobalVariable) getApplication();
db = new DatabaseManager(this);
db_user = new DatabaseUserManager(this);
final String [] url = {"https://png.pngtree.com/thumb_back/fh260/back_pic/00/03/20/63561dc0bf71922.jpg",
"https://placeit-assets.s3-accelerate.amazonaws.com/landing-pages/make-a-twitch-banner2/Twitch-Banner-Blue-1024x324.png",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQgYdaf-JhDiFVeQjL6ZRskiF1CRADiJfgDKI3PKBfCMrnnPcHP"};
final String [] paths = {"https://www.google.com/",
"https://www.youtube.com/",
"https://www.facebook.com/"};
Timer adtimer = new Timer();
adtimer.schedule(new TimerTask() {
int count = 0 ;
#Override
public void run() {
count++;
if(count >= url.length )
count = 0;
ActivityMain.this.runOnUiThread(new Runnable(){
#Override
public void run() {
System.out.println("test");
Picasso.get()
.load(String.format(url[count]))
.fit()
.into(Image_view);
}
});
Image_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uriUrl = Uri.parse(paths[count]);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
});
}
} , 200 , 5000);

Handler handleMessage not being called

I am running a simple handler and even when I do a handler.sendMessage(), the handleMessage method is not called.
Here is the Handler definition:
protected static class TimeoutHandler extends Handler {
private final WeakReference<PROQuestion> activity;
public TimeoutHandler(PROQuestion activity) {
this.activity = new WeakReference<PROQuestion>(activity);
}
#Override
public void handleMessage(Message msg) { //never gets called
boolean firstScreen = true;
if (activity.get() == null) {
removeCallbacksAndMessages(0);
} else {
Intent startNewActivityOpen = null;
startNewActivityOpen = new Intent(activity.get(), Home.class);
startNewActivityOpen.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Bundle bundle = activity.get().getIntent().getExtras();
if (bundle != null) startNewActivityOpen.putExtras(bundle);
activity.get().startActivity(startNewActivityOpen);
activity.get().finish();
}
}
I am calling the handler on the main thread of my onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TimeoutHandler handlerTimeout = new TimeoutHandler(this);
if (handlerTimeout != null) {
removeTimeout();
Message message = handlerTimeout.obtainMessage();
message.what = 100;
handlerTimeout.sendMessage(message);
//handlerTimeout.sendMessageAtTime(message, SystemClock.uptimeMillis() + GlobalVars.longTimeout);
}
if (handlerTimeout.hasMessages(100)) { //returns true
Log.d(getClass().getSimpleName(),"messages found");
}
}
Why is the handleMessage method never called? There are no error messages or crashes.

sinch conference call hung up right after it starts

I managed to start a conference call cut it closes right after I start it with HUNG_UP cause and I got this in my log:
11-03 17:28:08.940: E/sinch-android-rtc(19101): peermediaconnection: virtual void rebrtc::SetSDPObserver::OnFailure(const string&)Failed to set remote answer sdp: Offer and answer descriptions m-lines are not matching. Rejecting answer.
11-03 17:28:08.940: E/sinch-android-rtc(19101): mxp: Failed to set remote answer sdp: Offer and answer descriptions m-lines are not matching. Rejecting answer.
can anybody help me solve this please?
Edit:
my scenario is when a user clicks the call button I ask him if he wants to start a new call or join an already created one.
I managed to make my code from this question (Sinch conference call error) work as my GroupService class had some bugs.
I start my call like this:
Intent intent1 = new Intent(CreateGroupCallActivity.this,SinchClientService.class);
intent1.setAction(SinchClientService.ACTION_GROUP_CALL);
String id = String.valueOf(uid) + "-" + call_id.getText().toString();
intent1.putExtra(SinchClientService.INTENT_EXTRA_ID,id);
startService(intent1);
and in my SinchClientService:
if(intent.getAction().equals(ACTION_GROUP_CALL))
{
String id = intent.getStringExtra(INTENT_EXTRA_ID);
if(id != null)
groupCall(id);
}
public void groupCall(String id) {
if (mCallClient != null) {
Call call = mCallClient.callConference(id);
CurrentCall.currentCall = call;
Log.d("call", "entered");
Intent intent = new Intent(this, GroupCallService.class);
startService(intent);
}
}
nd here is my GroupCallService
public class GroupCallScreenActivity extends AppCompatActivity implements ServiceConnection {
private SinchClientService.MessageServiceInterface mMessageService;
private GroupCallService.GroupCallServiceInterface mCallService;
private UpdateReceiver mUpdateReceiver;
private ImageButton mEndCallButton;
private TextView mCallDuration;
private TextView mCallState;
private TextView mCallerName;
//private TextView locationview;
private ImageView user_pic;
private long mCallStart;
private Timer mTimer;
private UpdateCallDurationTask mDurationTask;
ImageButton chat;
ImageButton speaker;
ImageButton mic;
boolean speaker_on = false;
boolean mic_on = true;
PowerManager mPowerManager;
WakeLock mProximityWakeLock;
final static int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 32;
com.galsa.example.main.ImageLoader mImageLoader;
/*String location;
String longitude;
String latitude;*/
private class UpdateCallDurationTask extends TimerTask {
#Override
public void run() {
GroupCallScreenActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
updateCallDuration();
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
setContentView(R.layout.callscreen);
doBind();
mCallDuration = (TextView) findViewById(R.id.callDuration);
mCallerName = (TextView) findViewById(R.id.remoteUser);
mCallState = (TextView) findViewById(R.id.callState);
//locationview = (TextView) findViewById(R.id.location);
mEndCallButton = (ImageButton) findViewById(R.id.hangupButton);
chat = (ImageButton) findViewById(R.id.chat);
chat.setVisibility(View.GONE);
speaker = (ImageButton) findViewById(R.id.speaker);
mic = (ImageButton) findViewById(R.id.mic);
user_pic = (ImageView) findViewById(R.id.user_pic);
/*location = getIntent().getStringExtra("location");
longitude = getIntent().getStringExtra("longitde");
latitude = getIntent().getStringExtra("latitude");
locationview.setText(location);*/
mImageLoader = new com.galsa.example.main.ImageLoader(GroupCallScreenActivity.this, R.dimen.caller_image_height);
//mCallerName.setText(mCall.getRemoteUserId());
mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
mProximityWakeLock = mPowerManager.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, Utils.TAG);
/*chat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GroupCallScreenActivity.this, MessagingActivity.class);
intent.putExtra(SinchClientService.INTENT_EXTRA_ID, mCallService.getCallerId());
intent.putExtra(SinchClientService.INTENT_EXTRA_NAME, mCallService.getCallerName());
startActivity(intent);
}
});*/
speaker.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(speaker_on)
{
mMessageService.speakerOn(speaker_on);
speaker_on = false;
speaker.setImageResource(R.drawable.speaker_off);
}
else
{
mMessageService.speakerOn(speaker_on);
speaker_on = true;
speaker.setImageResource(R.drawable.speaker_on);
}
}
});
mic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mic_on)
{
mMessageService.micOn(mic_on);
mic_on = false;
mic.setImageResource(R.drawable.mic_off);
}
else
{
mMessageService.micOn(mic_on);
mic_on = true;
mic.setImageResource(R.drawable.mic_on);
}
}
});
mEndCallButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCallService.endCall();
}
});
mCallStart = System.currentTimeMillis();
}
private void doBind() {
Intent intent = new Intent(this, SinchClientService.class);
bindService(intent, this, BIND_AUTO_CREATE);
intent = new Intent(this, GroupCallService.class);
bindService(intent, this, BIND_AUTO_CREATE);
}
private void doUnbind() {
unbindService(this);
}
#Override
protected void onStart() {
super.onStart();
mUpdateReceiver = new UpdateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(GroupCallService.ACTION_FINISH_CALL_ACTIVITY);
filter.addAction(GroupCallService.ACTION_CHANGE_AUDIO_STREAM);
filter.addAction(GroupCallService.ACTION_UPDATE_CALL_STATE);
LocalBroadcastManager.getInstance(this).registerReceiver(mUpdateReceiver, filter);
}
#Override
public void onResume() {
super.onResume();
if(mProximityWakeLock != null && !mProximityWakeLock.isHeld()){
mProximityWakeLock.acquire();
}
mTimer = new Timer();
mDurationTask = new UpdateCallDurationTask();
mTimer.schedule(mDurationTask, 0, 500);
}
#Override
public void onPause() {
super.onPause();
if(isFinishing() && mProximityWakeLock != null && mProximityWakeLock.isHeld()){
mProximityWakeLock.release();
}
mDurationTask.cancel();
}
#Override
protected void onStop() {
super.onStop();
if(isFinishing() && mProximityWakeLock != null && mProximityWakeLock.isHeld()){
mProximityWakeLock.release();
}
if(mUpdateReceiver != null)
{
LocalBroadcastManager.getInstance(this).unregisterReceiver(mUpdateReceiver);
mUpdateReceiver = null;
}
}
#Override
public void onBackPressed() {
// User should exit activity by ending call, not by going back.
}
private void updateCallDuration() {
mCallDuration.setText(Utils.formatTimespan(System.currentTimeMillis() - mCallStart));
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if(iBinder instanceof GroupCallService.GroupCallServiceInterface)
{
mCallService = (GroupCallService.GroupCallServiceInterface) iBinder;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
ActionBar actionBar = getSupportActionBar();
if(mCallService.getCallerName() != null)
actionBar.setTitle(mCallService.getCallerName());
else
actionBar.setTitle("Group call");
actionBar.setIcon(R.drawable.callscreen);
if(mCallService.getCallerName() != null)
mCallerName.setText(mCallService.getCallerName());
else
mCallerName.setText("Group call");
mCallState.setText(mCallService.getCallState());
String pic = ChatDatabaseHandler.getInstance(this).getFriendpic(mCallService.getCallerId());
mImageLoader.displayImage(UserFunctions.hostImageDownloadURL + pic, user_pic);
}
else
mMessageService = (SinchClientService.MessageServiceInterface) iBinder;
mMessageService.enableMic();
mMessageService.disableSpeaker();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mMessageService = null;
mCallService = null;
}
#Override
public void onDestroy() {
if(mUpdateReceiver != null)
{
LocalBroadcastManager.getInstance(this).unregisterReceiver(mUpdateReceiver);
mUpdateReceiver = null;
}
doUnbind();
super.onDestroy();
}
private class UpdateReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if(GroupCallService.ACTION_FINISH_CALL_ACTIVITY.equals(intent.getAction()))
{
finish();
}
else if(GroupCallService.ACTION_CHANGE_AUDIO_STREAM.equals(intent.getAction()))
{
setVolumeControlStream(intent.getIntExtra("STREAM_TYPE", AudioManager.USE_DEFAULT_STREAM_TYPE));
}
else if(GroupCallService.ACTION_UPDATE_CALL_STATE.equals(intent.getAction()))
{
mCallState.setText(intent.getStringExtra("STATE"));
}
}
}
}
I start the call with the same way whether the user will start a new call or join a created one.

How to use Timer inside Handler?

I want to refresh an adapter every 10 seconds. I'm loading my ListView Adapter inside Handler, so what do I do? How do I use Timer? I want that whenever the value changes, the Adapter automatically refreshes ListView.
#SuppressLint("HandlerLeak")
Handler handle = new Handler() {
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
CommonObjects.hideProgress();
if (msg.what == 1) {
plotadapter = new PlotsAdapter(Plots.this, arrayplot);
plotslist.setAdapter(plotadapter);
}
if (msg.what == 2) {
Toast.makeText(Plots.this, "Server, Not Available!",
Toast.LENGTH_SHORT).show();
finish();
}
}
};
#Override
protected void onRestart() {
if(CommonObjects.getLogoutreject().equals("1") && CommonObjects.logout){
// CommonObjects.logout=false;
finish();
}
super.onRestart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.plots);
plotslist = (ListView) findViewById(R.id.plotslist);
back = (ImageView) findViewById(R.id.plotback);
bottomlayout = (RelativeLayout) findViewById(R.id.bottom_layout);
scroll_down = (ImageView) findViewById(R.id.down);
scroll_up = (ImageView) findViewById(R.id.up);
plotadapter = new PlotsAdapter(Plots.this, arrayplot);
plotslist.setAdapter(plotadapter);
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
#Override
public void run() {
if(condition)
{
// your code to check
plotadapter.notifyDataSetChanged();
}
handler.postDelayed(this, 1000);
}
}, 1000);

Categories

Resources