Switch state using intent [duplicate] - android

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(...)

Related

when back to activity from click music notification when click to next music view not update

When I click music notification and run activity. When music change the content of textview changed, but view not update, but when I run an activity independently, everything works fine and view updated.
In musicService class:
PendingIntent contentPendingIntent = PendingIntent.getActivity
(this, 0, new Intent(this, MusicPlayer.class), 0);
builder.setContentTitle(mMedia.getTitleMedia())
.setContentText(mMedia.getSingerName())
.setContentIntent(contentPendingIntent)
.setSmallIcon(R.drawable.ic_notification)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.addAction(restartAction)
.addAction(playPauseAction)
.addAction(nextMusic)
.setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(getApplicationContext(), PlaybackStateCompat.ACTION_STOP));
and my activity class
public class MusicPlayer extends AppCompatActivity implements ServiceConnection, CacheListener, SeekBar.OnSeekBarChangeListener, Player.EventListener {
private SimpleExoPlayerView mPlayerView;
public PlayerService mPlayerService;
private boolean mBound;
//______________________________________________________________________________________________
VolleyRequestHelper volleyRequestHelper;
//______________________________________________________________________________________________
public static MusicPlayer instance;
public ImageView download;
TextView title;
TextView artist;
SeekBar progressBar;
ImageView circleImageView;
ImageView album_art_blurred;
PlayPauseButton mPlayPause;
public AppBarLayout appBarLayout;
private final VideoProgressUpdater updater = new VideoProgressUpdater();
public DownloadProgressView downloadProgressView;
//______________________________________________________________________________________________
TextView songElapsedTime;
TextView songDuration;
int positionOfMusic = 0;
public Media media;
boolean initAlbum = false;
boolean startService = false;
boolean checkChangeMediaDetails = true;
//______________________________________________________________________________________________
RecyclerView recyclerViewArtist;
SimilarSongsAdapter similarSongsAdapter;
public List<Media> similarSongsList = new ArrayList<>();
//______________________________________________________________________________________________
int songElapsed = 0;
int songDurationTime = 0;
int videoProgress = 0;
int mediaServiceRun = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
instance = this;
volleyRequestHelper = VolleyRequestHelper.getInstance(getApplicationContext(), requestCompletedListener);
initView();
initRecyclerview();
Intent intent = getIntent();
mediaServiceRun = intent.getIntExtra("mediaServiceRun", 1);
if (mediaServiceRun == 1) {
Intent i = new Intent(this, PlayerService.class);
bindService(i, this, Context.BIND_AUTO_CREATE);
startService(i);
} else {
media = intent.getParcelableExtra("media");
switch (media.getCustomMediaType()) {
case "آهنگ آلبوم":
setMedia(media);
getAlbumTrack(media.getAlbumId());
break;
case "آلبوم":
initAlbum = true;
getAlbumTrack(media.getId());
break;
default:
setMedia(media);
Serach(media.getSingerName(), "1");
break;
}
selectMedia(media);
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(this);
mBound = false;
}
}
#Override
protected void onResume() {
super.onResume();
updater.start();
}
#Override
public void onPause() {
super.onPause();
updater.stop();
}
//_________________________ServiceConnected_and_ServiceDisconnected_____________________________
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
PlayerService.MyBinder b = (PlayerService.MyBinder) iBinder;
mPlayerService = b.getService();
mPlayerView.setUseController(false);
mPlayerView.setPlayer(mPlayerService.getExoPlayer());
if (mediaServiceRun == 1) {
similarSongsList = mPlayerService.getOnlineList();
initView();
initRecyclerview();
musicChange(mPlayerService.getPlayingMedia());
} else {
mPlayerService.getExoPlayer().addListener(this);
mPlayerService.setPlayingMedia(positionOfMusic);
setMusicInService(media, mPlayerService.getPlayingMedia());
if (similarSongsList != null && similarSongsList.size() != 0) {
mPlayerService.setOnlineList(similarSongsList);
}
}
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
//______________________________________________________________________________________________
//_______________________________________setMediaInView_________________________________________
public void setMedia(Media mediaL) {
media = mediaL;
bluredImage(mediaL.getCover());
Picasso.with(this).load(mediaL.getCover()).into(circleImageView);
title.setText(mediaL.getTitleMedia());
artist.setText(mediaL.getSingerName());
checkCachedState(mediaL.getStreamUrl());
checkChangeMediaDetails = false;
}
public void bluredImage(String IMAGE_URL) {
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
album_art_blurred.setImageBitmap(BlurImage.fastblur(bitmap, 1f, 50));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
album_art_blurred.setImageResource(R.mipmap.ic_launcher);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
album_art_blurred.setTag(target);
Picasso.with(this)
.load(IMAGE_URL)
.error(R.mipmap.ic_launcher)
.placeholder(R.mipmap.ic_launcher)
.into(target);
}
//______________________________________________________________________________________________
//______________________________________initView________________________________________________
public void initRecyclerview() {
recyclerViewArtist = (RecyclerView) findViewById(R.id.queue_recyclerview_horizontal);
recyclerViewArtist.setNestedScrollingEnabled(false);
recyclerViewArtist.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
LinearLayoutManager horizontalLayoutManagaertwo
= new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
recyclerViewArtist.setLayoutManager(horizontalLayoutManagaertwo);
similarSongsAdapter = new SimilarSongsAdapter(this, similarSongsList, recyclerViewArtist);
recyclerViewArtist.setAdapter(similarSongsAdapter);
}
public void initView() {
mPlayerView = (SimpleExoPlayerView) findViewById(R.id.simpleExoPlayerView);
appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
downloadProgressView = (DownloadProgressView) findViewById(R.id.downloadProgressView);
downloadProgressView.setPercentageColor(Color.parseColor("#ffffff"));
downloadProgressView.setDownloadedSizeColor(Color.parseColor("#ffffff"));
downloadProgressView.setTotalSizeColor(Color.parseColor("#ffffff"));
songElapsedTime = (TextView) findViewById(R.id.song_elapsed_time);
songDuration = (TextView) findViewById(R.id.song_duration);
progressBar = (SeekBar) findViewById(R.id.song_progress);
progressBar.setOnSeekBarChangeListener(this);
circleImageView = (ImageView) findViewById(R.id.album_art);
album_art_blurred = (ImageView) findViewById(R.id.album_art_blurred);
title = (TextView) findViewById(R.id.song_title);
artist = (TextView) findViewById(R.id.song_artist);
mPlayPause = (PlayPauseButton) findViewById(R.id.playpause);
download = (ImageView) findViewById(R.id.download);
if (SornaDownloadManager.inQueue) {
if (SornaDownloadManager.checkDownloadId(media.getId())) {
download.setVisibility(View.GONE);
downloadProgressView.show(SornaDownloadManager.lastDownloadID,
new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
}
}
}
//______________________________________________________________________________________________
//_________________________________Cache_and_UpdateProgressBar__________________________________
private void checkCachedState(String url) {
HttpProxyCacheServer proxy = TimberApp.getProxy(this);
boolean fullyCached = proxy.isCached(url);
if (fullyCached) {
progressBar.setSecondaryProgress(100);
}
proxy.registerCacheListener(this, url);
}
private void updateVideoProgress() {
if (mPlayerService != null)
try {
videoProgress = (int) (mPlayerService.getExoPlayer().getCurrentPosition() * 100 / mPlayerService.getExoPlayer().getDuration());
} catch (Exception e) {
}
progressBar.setProgress(videoProgress);
}
private final class VideoProgressUpdater extends Handler {
public void start() {
sendEmptyMessage(0);
}
public void stop() {
removeMessages(0);
}
#Override
public void handleMessage(Message msg) {
updateVideoProgress();
sendEmptyMessageDelayed(0, 500);
if (mPlayerService != null) {
try {
songElapsed = (int) mPlayerService.getExoPlayer().getCurrentPosition();
songDurationTime = (int) mPlayerService.getExoPlayer().getDuration();
} catch (Exception e) {
}
}
songElapsedTime.setText(millisecondsTOminutes.milliSecondsToTimer(songElapsed));
songDuration.setText(millisecondsTOminutes.milliSecondsToTimer(songDurationTime));
}
}
#Override
public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
progressBar.setSecondaryProgress(percentsAvailable);
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
void seekVideo() {
int videoPosition = (int) (mPlayerService.getExoPlayer().getDuration() * progressBar.getProgress() / 100);
mPlayerService.getExoPlayer().seekTo(videoPosition);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekVideo();
songElapsedTime.setText(millisecondsTOminutes.milliSecondsToTimer(mPlayerService.getExoPlayer().getCurrentPosition()) + "");
}
//______________________________________________________________________________________________
//____________________________________setButtonsFuction_________________________________________
public void setFunc(View v) {
switch (v.getId()) {
case R.id.playpause:
if (!mPlayPause.isPlayed()) {
setPlayButton(true);
if (!startService) {
setStopService();
setStartService();
onlinePlay(media.getId());
} else {
mPlayerService.playTrack();
}
} else {
setPlayButton(false);
mPlayerService.pauseTrack();
}
break;
case R.id.next:
mPlayerService.nextTrack();
//positionOfMusic = mPlayerService.getPlayingMedia();
break;
case R.id.previous:
mPlayerService.previousTrack();
//positionOfMusic = mPlayerService.getPlayingMedia();
break;
case R.id.download:
showPopup(media);
break;
case R.id.share:
share.shareTrack(media, this);
break;
}
}
public void showPopup(final Media media) {
View popupView = LayoutInflater.from(this).inflate(R.layout.popup_layout, null);
final PopupWindow popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT
, WindowManager.LayoutParams.MATCH_PARENT);
popupWindow.setOutsideTouchable(false);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(popupView, Gravity.CENTER, 1, 1);
Button dnlow = (Button) popupView.findViewById(R.id.dnlow);
Button dnhigh = (Button) popupView.findViewById(R.id.dnhigh);
if (media.getDownloadLinksList128().matches("noLink"))
dnlow.setVisibility(View.GONE);
if (media.getDownloadLinksList320().matches("noLink"))
dnhigh.setVisibility(View.GONE);
dnlow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SornaDownloadManager sornaDownloadManager = SornaDownloadManager.getInstance(getApplicationContext());
long downloadID = sornaDownloadManager.AddForDownload(media.getDownloadLinksList128(),
media.getTitleMedia() + "-" + media.getSingerName(), media.getId());
downloadProgressView.show(downloadID, new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
popupWindow.dismiss();
}
});
dnhigh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SornaDownloadManager sornaDownloadManager = SornaDownloadManager.getInstance(getApplicationContext());
long downloadID = sornaDownloadManager.AddForDownload(media.getDownloadLinksList320(),
media.getTitleMedia() + "-" + media.getSingerName(), media.getId());
downloadProgressView.show(downloadID, new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(popupView, 0, 0);
}
//______________________________________________________________________________________________
//__________________________________GetDataFromServer___________________________________________
public void Serach(String searchQuery, String page) {
updateData();
volleyRequestHelper.RequestFetchSearchMedia
(constantsURL.REQUEST_FETCH_SIMILAR_SONGS, searchQuery, page, false);
}
public void getAlbumTrack(String albumId) {
updateData();
volleyRequestHelper.RequestFetchAlbumTrack
(constantsURL.REQUEST_FETCH_ALBUM_TRACKS, albumId, false);
}
public void selectMedia(final Media media) {
if (!constants.refLogId.matches(""))
volleyRequestHelper.requestSetLog
(constantsURL.REQUEST_SET_LOG, "selectSearchResult", media.getId(), constants.refLogId, false);
}
public void onlinePlay(final String mediaid) {
volleyRequestHelper.requestSetLog
(constantsURL.REQUEST_SET_LOG, "onlinePlay", mediaid, constants.refLogId, false);
}
public void updateData() {
similarSongsAdapter.notifyDataSetChanged();
similarSongsAdapter.setLoaded();
}
public void parseJson(String response, List<Media> arrayList) {
try {
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(response);
JSONObject jsonObject = new JSONObject(String.valueOf(json));
JSONArray arrey = jsonObject.getJSONArray("result");
if (!media.getCustomMediaType().matches("آلبوم"))
arrayList.add(media);
for (int i = 0; i < arrey.length(); i++) {
JSONObject j = arrey.getJSONObject(i);
Media mdia = new Media(j);
if (!media.getId().matches(mdia.getId()) && !mdia.getCustomMediaType().matches("آلبوم"))
arrayList.add(mdia);
}
} catch (Exception e) {
}
if (mPlayerService != null) {
mPlayerService.setOnlineList(similarSongsList);
}
}
private VolleyRequestHelper.OnRequestCompletedListener requestCompletedListener =
new VolleyRequestHelper.OnRequestCompletedListener() {
#Override
public void onRequestCompleted(String requestName, boolean status,
String response, String errorMessage) {
//homeView.hideProgress();
switch (requestName) {
case "SIMILAR_SONGS":
if (status) {
parseJson(response, similarSongsList);
updateData();
}
break;
case "ALBUM_TRACKS":
if (status) {
parseJson(response, similarSongsList);
updateData();
if (initAlbum) {
setMedia(similarSongsList.get(0));
}
}
break;
}
}
};
//_______________________________________EXOPLAYER______________________________________________
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
if (checkChangeMediaDetails) {
musicChange(mPlayerService.getPlayingMedia());
} else checkChangeMediaDetails = true;
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if ((playbackState == Player.STATE_READY) && playWhenReady) {
if (!mPlayPause.isPlayed()) {
setPlayButton(true);
}
} else if ((playbackState == Player.STATE_READY)) {
setPlayButton(false);
} else if (playbackState == Player.STATE_ENDED) {
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity() {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
//______________________________________________________________________________________________
public void setStartService() {
Intent intent = new Intent(this, PlayerService.class);
bindService(intent, this, Context.BIND_AUTO_CREATE);
startService(intent);
startService = true;
}
public void setStopService() {
Intent intentStop = new Intent(this, PlayerService.class);
stopService(intentStop);
}
public void setPlayButton(boolean playButton) {
mPlayPause.setPlayed(playButton);
mPlayPause.startAnimation();
}
public void setMusicInService(Media mMedia, int position) {
positionOfMusic = position;
if (mPlayerService != null) {
mPlayerService.setPlayMedia(mMedia, position);
} else {
setStartService();
setMedia(mMedia);
}
//positionOfMusic = position;
/*if (mPlayerService != null) {
mPlayerService.setMediaUri(mMedia.getStreamUrl());
mPlayerService.setMedia(mMedia);
mPlayerService.setPlayingMedia(position);
mPlayerService.preparePlayer();
} else {
positionOfMusic = position;
setStartService();
setMedia(mMedia);
}*/
}
public void musicChange(int newPosition) {
if (similarSongsList != null && similarSongsList.size() != 0) {
setMedia(similarSongsList.get(newPosition));
similarSongsAdapter.setPlayPosition(newPosition);
similarSongsAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder)
{
PlayerService.MyBinder b = (PlayerService.MyBinder) iBinder;
mPlayerService = b.getService();
mPlayerView.setUseController(false);
mPlayerView.setPlayer(mPlayerService.getExoPlayer());
if (mediaServiceRun == 1) {
similarSongsList = mPlayerService.getOnlineList();
initView();
initRecyclerview();
musicChange(mPlayerService.getPlayingMedia());
} else {
mPlayerService.getExoPlayer().addListener(this);
mPlayerService.setPlayingMedia(positionOfMusic);
setMusicInService(media, mPlayerService.getPlayingMedia());
if (similarSongsList != null && similarSongsList.size() != 0) {
mPlayerService.setOnlineList(similarSongsList);
}
}
mBound = true;
}

How to convert Speech to Text

Using SpeechRecognizer class of Android.
private void initRecord() {
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
}
Please use below code for converting Speech to Text. its the working code.just Copy and paste Below code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
recordImg = (ImageView) findViewById(R.id.button);
checkPermission();
initRecord();
recordImg.setOnTouchListener(this);
}
private void initRecord() {
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null)
editText.setText(matches.get(0));
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
//when the user removed the fingure...
mSpeechRecognizer.stopListening();
editText.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
editText.setText("");
editText.setHint("You will see input here");
break;
}
return false;
}

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.

Quickblox Android how to get the first message from incoming chat?

I'm using quickblox android sdk for my chat application. I know that when opponent user starts the conversation QBPrivateChatManagerListener -> chatCreated() event get fired. Below is my code. When chatCreated is fired I load the chat Fragment. In the chat fragment I have implemented the QBMessageListenerImpl interface. Problem here is that I don't get the first message from processMessage(). But I get the second message. So my question is how can I read the very first message that opponent user is sending ?
#Override
public void chatCreated(final QBPrivateChat qbPrivateChat, boolean b) {
ShowMessage("Incoming chat!!");
if(!b)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
CreateNewChatForIncoming(qbPrivateChat);
}
});
}
}
public void CreateNewChatForIncoming(QBPrivateChat qbPrivateChat) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
PrivateChatFragment privateChatFragment = new PrivateChatFragment();
privateChatFragment.setOpponentuser(null);
privateChatFragment.setIncomingChat(qbPrivateChat);
HashMap<Integer, QBUser> allusers = applicationSingleton.getAllusers();
String title = allusers.get(qbPrivateChat.getParticipant()).getFullName();
if (title != null)
this.setTitle(title);
ft.replace(R.id.content_frame, privateChatFragment);
ft.commit();
}
/*---------------Private chat Fragment-------------------------*/
public class PrivateChatFragment extends SherlockFragment {
TextView txtmsg;
MessageAdaptor messageAdaptor;
ListView listView;
boolean ismode = true;
PrivateChat privateChat;
private QBUser opponentuser;
private QBPrivateChat incomingChat;
int opponentuserid;
ApplicationSingleton applicationSingleton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chattabfragment, container, false);
txtmsg = (TextView) view.findViewById(R.id.txtmsg);
SetFont(txtmsg);
applicationSingleton = (ApplicationSingleton)getSherlockActivity().getApplication();
messageAdaptor = new MessageAdaptor(this.getActivity().getApplicationContext(), R.layout.msg_list_item_inbound);
if (opponentuser != null) {
opponentuserid = opponentuser.getId();
HashMap<Integer, PrivateChat> allpvtchats = applicationSingleton.getAllpvtchats();
if(allpvtchats.containsKey(opponentuserid)) {
privateChat = applicationSingleton.getAllpvtchats().get(opponentuserid);
}
else {
privateChat = new PrivateChat(this, opponentuserid);
applicationSingleton.getAllpvtchats().put(opponentuserid,privateChat);
}
List<ChatMessage> allmsgs = GetMessageHistory(opponentuser);
if (allmsgs != null) {
ShowMessage("setting history");
messageAdaptor.LoadNewItems(allmsgs);
messageAdaptor.notifyDataSetChanged();
messageAdaptor.notifyDataSetInvalidated();
}
} else if (incomingChat != null) {
opponentuserid = incomingChat.getParticipant();
privateChat = new PrivateChat(this, incomingChat);
}
listView = (ListView) view.findViewById(R.id.listview_msg);
listView.setAdapter(messageAdaptor);
txtmsg.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
ChatMessage msg = new ChatMessage();
msg.setOutbound(true);
msg.setImg(R.drawable.boy1);
msg.setTime("10:30am");
msg.setMessage(txtmsg.getText().toString());
messageAdaptor.add(msg);
txtmsg.setText("");
scrolToBottom();
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody(msg.getMessage());
//chatMessage.setProperty("name", opponentuser.getFullName());
chatMessage.setSaveToHistory(true);
chatMessage.setMarkable(true);
try {
privateChat.sendMessage(chatMessage);
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
return true;
}
return false;
}
});
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroyView() {
super.onDestroyView();
ApplicationSingleton applicationSingleton = (ApplicationSingleton) this.getActivity().getApplication();
HashMap<Integer, List<ChatMessage>> allchats = applicationSingleton.getAllchats();
allchats.put(opponentuserid, messageAdaptor.GetAllMessages());
applicationSingleton.setAllchats(allchats);
}
private List<ChatMessage> GetMessageHistory(QBUser opnnentuser) {
ApplicationSingleton applicationSingleton = (ApplicationSingleton) this.getActivity().getApplication();
HashMap<Integer, List<ChatMessage>> allchats = applicationSingleton.getAllchats();
if (allchats.containsKey(opnnentuser.getId())) {
return allchats.get(opnnentuser.getId());
} else {
return null;
}
}
void SetFont(TextView view) {
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/LatoRegular.ttf");
view.setTypeface(font);
}
public void scrolToBottom() {
listView.post(new Runnable() {
#Override
public void run() {
listView.setSelection(messageAdaptor.getCount() - 1);
}
});
}
public void UpdateAdaptor(final ChatMessage chatMessage) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (messageAdaptor != null) {
messageAdaptor.add(chatMessage);
messageAdaptor.notifyDataSetChanged();
scrolToBottom();
}
}
});
}
public void setOpponentuser(QBUser opponentuser) {
this.opponentuser = opponentuser;
}
public void setIncomingChat(QBPrivateChat incomingChat) {
this.incomingChat = incomingChat;
}
public void SendNotification(String title, String message) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getSherlockActivity())
.setSmallIcon(R.drawable.boy6_small)
.setContentTitle(title)
.setContentText(message);
int mId = GetNotificationid();
Intent resultIntent = new Intent(getSherlockActivity(), SideMenuActivity.class);
resultIntent.putExtra(GlobalData.OP_ID, opponentuser.getId());
resultIntent.putExtra(GlobalData.NOTIFY_MODE, true);
resultIntent.putExtra(GlobalData.NOTIFY_ID, mId);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getSherlockActivity());
stackBuilder.addParentStack(SideMenuActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSherlockActivity().getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());
}
private void ShowMessage(final String msg) {
Runnable mrunnable = new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
};
getActivity().runOnUiThread(mrunnable);
}
private int GetNotificationid()
{
Calendar c = Calendar.getInstance();
int milsec = c.get(Calendar.MILLISECOND);
return milsec;
}
}
/* --------------------Privatechat class------------------- */
public class PrivateChat extends QBMessageListenerImpl<QBPrivateChat>{
private QBPrivateChatManager privateChatManager;
private QBPrivateChat privateChat;
private PrivateChatFragment currentContext;
private ApplicationSingleton applicationSingleton;
public PrivateChat(PrivateChatFragment context,Integer opponentID) {
currentContext = context;
applicationSingleton = (ApplicationSingleton)currentContext.getSherlockActivity().getApplication();
privateChatManager = applicationSingleton.getChatService().getPrivateChatManager();
// init private chat
//
privateChat = privateChatManager.getChat(opponentID);
if (privateChat == null) {
privateChat = privateChatManager.createChat(opponentID, this);
}else{
privateChat.addMessageListener(this);
}
}
public PrivateChat(PrivateChatFragment context,QBPrivateChat incomingChat) {
privateChat = incomingChat;
privateChat.addMessageListener(this);
currentContext = context;
}
public void sendMessage(QBChatMessage message) throws XMPPException, SmackException.NotConnectedException {
privateChat.sendMessage(message);
}
public void release() {
privateChat.removeMessageListener(this);
}
#Override
public void processMessage(QBPrivateChat chat, QBChatMessage message) {
Log.e("Anuradha-message",message.getBody());
ChatMessage msg = new ChatMessage();
msg.setOutbound(false);
msg.setImg(R.drawable.boy2);
msg.setTime("10:30am");
msg.setMessage(message.getBody());
currentContext.UpdateAdaptor(msg);
if(applicationSingleton.isAppBackground()) {
HashMap<Integer,QBUser> allusers = applicationSingleton.getAllusers();
QBUser user = allusers.get(message.getSenderId());
currentContext.SendNotification(user.getFullName().toString(),"says "+message.getBody());
}
}
#Override
public void processError(QBPrivateChat chat, QBChatException error, QBChatMessage originChatMessage){
}
#Override
public void processMessageDelivered(QBPrivateChat privateChat, String messageID){
}
#Override
public void processMessageRead(QBPrivateChat privateChat, String messageID){
ShowMessage("msg read : "+messageID);
}
private void ShowMessage(final String msg) {
Runnable mrunnable = new Runnable() {
#Override
public void run() {
Toast.makeText(currentContext.getActivity(), msg, Toast.LENGTH_LONG).show();
}
};
currentContext.getActivity().runOnUiThread(mrunnable);
}
}
Try to change
privateChat = privateChatManager.getChat(opponentID);`enter code here` if (privateChat == null) {
privateChat = privateChatManager.createChat(opponentID, this);
}else{
privateChat.addMessageListener(this);
}

to
if (privateChat == null) {
privateChat = privateChatManager.createChat(opponentID, this);
}
privateChat.addMessageListener(this);

How to Show ListView Items in Tabs

In Contacts Tab, trying to fetch list of all Facebook Friends
In Month Tab, trying to fetch list of Facebook Friends those Birthdays in Current Month
In Week Tab, trying to fetch list of Facebook Friends those Birthdays in Current Week
I have written code for all and i am not getting any error while build and run my program, but i am not getting list of friends in any of the Tab.
Please let me know, where i am doing silly mistake...where i am missing..
TabSample.Java :-
public class TabSample extends TabActivity {
String response;
private static JSONArray jsonArray;
public static TabHost mTabHost;
private MyFacebook fb = MyFacebook.getInstance();
public static MyLocalDB db = null;
private BcReceiver bcr = null;
private BcReceiverAlarm bcra = null;
private PendingIntent mAlarmSender;
private boolean isAlarmSet;
private ProgressDialog busyDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAlarmSender = PendingIntent.getService(TabSample.this, 0, new Intent(
TabSample.this, BdRemService.class), 0);
setContentView(R.layout.main);
if (db == null) {
db = new MyLocalDB(this);
db.open();
}
if (!fb.isReady()) {
Log.v(TAG, "TabSample- initiating facebook");
fb.init(this);// after finishing, this will call loadContents itself
} else {
loadContents();
}
busyDialog = new ProgressDialog(this);
busyDialog.setIndeterminate(true);
busyDialog.setMessage("Refreshing");
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
response = getIntent().getStringExtra("FRIENDS");
try {
jsonArray = new JSONArray(response);
} catch (JSONException e) {
FacebookUtility.displayMessageBox(this,
this.getString(R.string.json_failed));
}
setTabs();
}
private void setTabs() {
addTab("Contacts", com.chr.tatu.sample.friendslist.ContactTab.class);
addTab("Month", com.chr.tatu.sample.friendslist.MonthTab.class);
addTab("Week", com.chr.tatu.sample.friendslist.WeekTab.class);
}
private void setupTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
}
private void setupTab(final View view, final String tag, Intent intent,
int id) {
View tabview = createTabView(mTabHost.getContext(), tag, id);
TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview)
.setContent(intent);
mTabHost.addTab(setContent);
}
private void addTab(String labelId, Class<?> c) {
TabHost tabHost = getTabHost();
Intent intent = new Intent(this, c);
intent.putExtra("FRIENDS", response);
TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(
R.layout.tab_indicator, getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
spec.setIndicator(tabIndicator);
spec.setContent(intent);
tabHost.addTab(spec);
}
private static View createTabView(final Context context, final String text,
final int id)
{
View view = LayoutInflater.from(context).inflate(
R.layout.tab_indicator, null);
return view;
}
#Override
protected void onResume() {
if (bcr == null) {
bcr = new BcReceiver();
registerReceiver(bcr, new IntentFilter(MyUtils.BIRTHDAY_ALERT));
}
if (bcra == null) {
bcra = new BcReceiverAlarm();
registerReceiver(bcra, new IntentFilter(MyUtils.ALARM_RESET));
}
super.onResume();
}
public void loadContents() {
if (fb.getFriendsCount() > 0) {
return;
}
fb.setMyFriends(db.getAllFriends());
if (fb.getFriendsCount() > 0) {
notifyTabSample(Note.FRIENDLIST_CHANGED);
} else {
fb.reLoadAllFriends();
}
// 4. initiate alarm
if (!isAlarmSet) {
setAlarm(true);
}
}
private void setAlarm(boolean isON) {
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
if (isON) {
am.setRepeating(AlarmManager.RTC_WAKEUP, MyUtils
.getAlarmStartTimeAsLong(MyUtils.getAlarmHour(), MyUtils
.getAlarmMinute()), 24 * 60 * 60 * 1000,
mAlarmSender);
isAlarmSet = true;
Log.v(TAG, "TabSample- alarm set");
} else {
am.cancel(mAlarmSender);
isAlarmSet = true;
Log.v(TAG, "TabSample- alarm cancelled");
}
}
public void notifyTabSample(Note what) {
switch (what) {
case FRIENDLIST_RELOADED:
db.syncFriends(fb.getMyFriends());
sendBroadcast(new Intent(MyUtils.FRIENDLIST_CHANGED));
break;
case FRIENDLIST_CHANGED:
sendBroadcast(new Intent(MyUtils.FRIENDLIST_CHANGED));
// setup timer
break;
default:
break;
}
}
ContactTab.Java :-
public class ContactTab extends ListActivity {
private MyFacebook fb = MyFacebook.getInstance();
private BcReceiver bcr = null;
private MyAdapter adapter;
private List<MyFriend> list;
private ProgressDialog busyDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
busyDialog = new ProgressDialog(this);
busyDialog.setIndeterminate(true);
busyDialog.setMessage("Refreshing");
}
private void refreshList() {
new Thread() {
public void run() {
list = fb.getAllFriends();
Log.v(TAG, "contactstab- refresh called. " + list.size());
adapter = new MyAdapter(ContactTab.this, list);
handler.sendEmptyMessage(0);
}
}.start();
}
#Override
protected void onResume() {
if (bcr == null) {
bcr = new BcReceiver();
registerReceiver(bcr, new IntentFilter(MyUtils.FRIENDLIST_CHANGED));
}
refreshList();
super.onResume();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
MyFriend friend = (MyFriend) this.getListAdapter().getItem(position);
Intent intent = new Intent(ContactTab.this, PersonalGreeting.class);
intent.putExtra("fbID", friend.getFbID());
intent.putExtra("name", friend.getName());
intent.putExtra("pic", friend.getPic());
startActivity(intent);
}
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication()).inflate(R.layout.menu, menu);
return (super.onPrepareOptionsMenu(menu));
}
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.globalGreeting:
intent = new Intent(ContactTab.this, com.chr.tatu.sample.friendslist.GlobalGreeting.class);
startActivity(intent);
break;
case R.id.Settings:
intent = new Intent(ContactTab.this, com.chr.tatu.sample.friendslist.Settings.class);
startActivity(intent);
}
return (super.onOptionsItemSelected(item));
}
public class BcReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
runOnUiThread(new Runnable() {
public void run() {
refreshList();
}
});
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
setListAdapter(adapter);
//busyDialog.dismiss();
}
};
}
MonthTab.Java :-
public class MonthTab extends ListActivity {
private MyFacebook fb = MyFacebook.getInstance();
private BcReceiver bcr = null;
private MyAdapter adapter;
private List<MyFriend> list;
private ProgressDialog busyDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
busyDialog = new ProgressDialog(this);
busyDialog.setIndeterminate(true);
busyDialog.setMessage("Please wait ...");
busyDialog.show();
refreshList();
}
private void refreshList() {
// list = fb.getFilteredFriends(Filter.MONTH);
list = fb.getFilteredFriends(Filter.MONTH);
adapter = new MyAdapter(MonthTab.this, list);
setListAdapter(adapter);
busyDialog.dismiss();
}
#Override
protected void onResume() {
if (bcr == null) {
bcr = new BcReceiver();
registerReceiver(bcr, new IntentFilter(MyUtils.FRIENDLIST_CHANGED));
}
super.onResume();
}
#Override
#SuppressWarnings("unchecked")
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
MyFriend friend = (MyFriend) this.getListAdapter().getItem(position);
Intent intent = new Intent(MonthTab.this, PersonalGreeting.class);
intent.putExtra("fbID", friend.getFbID());
intent.putExtra("name", friend.getName());
startActivity(intent);
}
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication()).inflate(R.layout.menu, menu);
return (super.onPrepareOptionsMenu(menu));
}
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.globalGreeting:
intent = new Intent(MonthTab.this, GlobalGreeting.class);
startActivity(intent);
break;
case R.id.Settings:
intent = new Intent(MonthTab.this, Settings.class);
startActivity(intent);
}
return (super.onOptionsItemSelected(item));
}
public class BcReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
runOnUiThread(new Runnable() {
public void run() {
refreshList();
}
});
}
}
}

Categories

Resources