sinch conference call hung up right after it starts - android

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.

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

How do I override the actions of the ExoPlayer buttons

I created my layout for the ExoPlayer buttons
***
<ImageButton
android:id="#id/exo_play"
android:layout_width="50dp"
android:layout_height="50dp"
android:onClick="onPlayClick"
android:background="#drawable/btn_play" />
<ImageButton
android:id="#id/exo_pause"
android:layout_width="50dp"
android:layout_height="50dp"
android:onClick="onPauseClick"
android:background="#drawable/btn_pause" />
***
I have a program in my program that starts and stops from the PlayerActivity. How to make the service stop when clicking on the pause button in the EcxoPlayer, and when you click on play, the service was restarted?
Code PlayerActivity
public class PlayerActivity extends AppCompatActivity {
private int id;
private String title;
private String autor;
private String file;
private String img;
private String MAYBE_ACTION = "MAYBE_ACTION";
static boolean isPlay = false;
ImageButton btnPLayPause;
private TextView txtRadio;
private TextView txtTitle;
private RoundedImageView imgRadio;
private ImageButton exo_pause;
private ImageButton exo_play;
private String internetStatus = "";
BroadcastReceiver br;
BroadcastReceiver serviceReceiver;
public final static String SERVICE_PARAM = "param";
public final static int SERVICE_STATUS = 0;
public final static String BROADCAST_ACTION = "ru.myapps";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
id = getIntent().getExtras().getInt("id");
title = getIntent().getExtras().getString("title");
autor = getIntent().getExtras().getString("autor");
file = "link";
img = getIntent().getExtras().getString("img");
RadioPlayer.simpleExoPlayerView = new SimpleExoPlayerView(this);
RadioPlayer.simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player);
btnPLayPause = (ImageButton) findViewById(R.id.btnPLayPause);
txtRadio = (TextView) findViewById(R.id.txtRadio);
imgRadio = (RoundedImageView) findViewById(R.id.imgRadio);
exo_pause = (ImageButton) findViewById(R.id.exo_pause);
exo_play = (ImageButton) findViewById(R.id.exo_play);
setTitle(title);
txtRadio.setText(title);
br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
IntentFilter intentFilter = new IntentFilter(MAYBE_ACTION);
registerReceiver(br, intentFilter);
if (NetworkUtil.getConnectivityStatus(this) != 0) {
startPlayerService();
exo_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isPlay) {
stopPlayerService();
}
}
});
exo_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (NetworkUtil.getConnectivityStatus(PlayerActivity.this) != 0 ) {
if (!isPlay) {
startPlayerService();
}
}
}
});
}
}
#Override
protected void onStart() {
super.onStart();
}
public void startPlayerService() {
Intent serviceIntent = new Intent(PlayerActivity.this, PlayerService.class);
serviceIntent.putExtra(PlayerService.KEY_STREAM, file);
serviceIntent.putExtra(PlayerService.KEY_RADIO, title);
serviceIntent.setAction(PlayerConstants.ACTION.STARTFOREGROUND_ACTION);
startService(serviceIntent);
isPlay = true;
btnPLayPause.setImageResource(R.drawable.icon_stop);
exo_pause.setVisibility(View.VISIBLE);
exo_play.setVisibility(View.GONE);
}
private void stopPlayerService() {
Intent serviceIntent = new Intent(PlayerActivity.this, PlayerService.class);
serviceIntent.setAction(PlayerConstants.ACTION.STOPFOREGROUND_ACTION);
stopService(serviceIntent);
isPlay = false;
btnPLayPause.setImageResource(R.drawable.icon_play);
exo_pause.setVisibility(View.GONE);
exo_play.setVisibility(View.VISIBLE);
}
private BroadcastReceiver NetworkChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
internetStatus = NetworkUtil.getConnectivityStatusString(context);
//Toast.makeText(context, internetStatus, Toast.LENGTH_LONG).show();
}
};
#Override
protected void onResume() {
super.onResume();
serviceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int serviceStatus = intent.getIntExtra(SERVICE_PARAM, 0);
if (serviceStatus == SERVICE_STATUS) {
btnPLayPause.setImageResource(R.drawable.icon_play);
}
}
};
IntentFilter filter = new IntentFilter(BROADCAST_ACTION);
registerReceiver(serviceReceiver, filter);
registerReceiver(NetworkChangeReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
registerReceiver(NetworkChangeReceiver, new IntentFilter("android.net.wifi.WIFI_STATE_CHANGED"));
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (NetworkChangeReceiver != null) unregisterReceiver(NetworkChangeReceiver);
unregisterReceiver(br);
unregisterReceiver(serviceReceiver);
}
}
I tried to implement the actions of buttons in onresume but when I pause the service it stops and the play button does not play
Your OnClickListener should be in OnCreate, try this and let me know:
public class PlayerActivity extends AppCompatActivity {
private int id;
private String title;
private String autor;
private String file;
private String img;
private String MAYBE_ACTION = "MAYBE_ACTION";
static boolean isPlay = false;
ImageButton btnPLayPause;
private TextView txtRadio;
private TextView txtTitle;
private RoundedImageView imgRadio;
private SimpleExoPlayerView simpleExoPlayerView;
private SimpleExoPlayer player;
private ImageButton exo_pause;
private ImageButton exo_play;
public static String LOG_TAG = "my_log";
private String internetStatus = "";
BroadcastReceiver br;
BroadcastReceiver serviceReceiver;
private AsyncTask jsonTask;
public final static String SERVICE_PARAM = "param";
public final static int SERVICE_STATUS = 0;
public final static String BROADCAST_ACTION = "ru.myapps";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
id = getIntent().getExtras().getInt("id");
title = getIntent().getExtras().getString("title");
autor = getIntent().getExtras().getString("autor");
file = "link_mp3_files";
img = getIntent().getExtras().getString("img");
RadioPlayer.simpleExoPlayerView = new SimpleExoPlayerView(this);
RadioPlayer.simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player);
btnPLayPause = (ImageButton) findViewById(R.id.btnPLayPause);
txtRadio = (TextView) findViewById(R.id.txtRadio);
imgRadio = (RoundedImageView) findViewById(R.id.imgRadio);
exo_pause = (ImageButton) findViewById(R.id.exo_pause);
exo_play = (ImageButton) findViewById(R.id.exo_play);
setTitle(title);
txtRadio.setText(title);
if (NetworkUtil.getConnectivityStatus(this) != 0) {
startPlayerService();
}
exo_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isPlay) {
stopPlayerService();
}
}
});
exo_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (NetworkUtil.getConnectivityStatus(PlayerActivity.this) != 0 ) {
if (isPlay) {
startPlayerService();
}
}
}
});
br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
IntentFilter intentFilter = new IntentFilter(MAYBE_ACTION);
registerReceiver(br, intentFilter);
}
#Override
protected void onStart() {
super.onStart();
}
public void startPlayerService() {
Intent serviceIntent = new Intent(PlayerActivity.this, PlayerService.class);
serviceIntent.putExtra(PlayerService.KEY_STREAM, file);
serviceIntent.putExtra(PlayerService.KEY_RADIO, title);
serviceIntent.setAction(PlayerConstants.ACTION.STARTFOREGROUND_ACTION);
startService(serviceIntent);
isPlay = true;
btnPLayPause.setImageResource(R.drawable.icon_stop);
if(exo_play.getVisibility() == View.VISIBLE) {
exo_play.setVisibility(View.GONE);
exo_pause.setVisibility(View.VISIBLE);
}
}
private void stopPlayerService() {
Intent serviceIntent = new Intent(PlayerActivity.this, PlayerService.class);
serviceIntent.setAction(PlayerConstants.ACTION.STOPFOREGROUND_ACTION);
stopService(serviceIntent);
isPlay = false;
btnPLayPause.setImageResource(R.drawable.icon_play);
if(exo_pause.getVisibility() == View.VISIBLE) {
exo_pause.setVisibility(View.GONE);
exo_play.setVisibility(View.VISIBLE);
}
}
private BroadcastReceiver NetworkChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
internetStatus = NetworkUtil.getConnectivityStatusString(context);
//Toast.makeText(context, internetStatus, Toast.LENGTH_LONG).show();
}
};
#Override
protected void onResume() {
super.onResume();
serviceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int serviceStatus = intent.getIntExtra(SERVICE_PARAM, 0);
if (serviceStatus == SERVICE_STATUS) {
btnPLayPause.setImageResource(R.drawable.icon_play);
}
}
};
IntentFilter filter = new IntentFilter(BROADCAST_ACTION);
registerReceiver(serviceReceiver, filter);
registerReceiver(NetworkChangeReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
registerReceiver(NetworkChangeReceiver, new IntentFilter("android.net.wifi.WIFI_STATE_CHANGED"));
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (NetworkChangeReceiver != null) unregisterReceiver(NetworkChangeReceiver);
unregisterReceiver(br);
unregisterReceiver(serviceReceiver);
}
}
In OnResume you can check if it is running or not then stoo it if you would like to.
Your problem is that you never called startPlayerService(); when exo_play is tapped. Please see exo_play.setOnClickListener. I also removed the else statement as it is unnecessary.

Cannot stop timer in Android? How to solve it?

I am writing a class to control start and stop timer in Android. The controller is an Activity that will send start or stop value. In the TimerControl class, I write two functions that use to start and stop the timer. I can start the timer, but I cannot stop it. How can I solve it? This is my code
//In Controller class
//===========Start========
Intent smsTimer = new Intent(getApplicationContext(), TimmerControl.class);
smsTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsTimer.putExtra("input_timer", "start");
getApplicationContext().startActivity(smsTimer);
//===========Stop========
Intent smsTimer = new Intent(getApplicationContext(), TimmerControl.class);
smsTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsTimer.putExtra("input_timer", "stop");
getApplicationContext().startActivity(smsTimer);
This is my code of TimerControl
public class TimmerControl extends Activity {
private CountDownTimer timer_SMS;
private String TAG="TimmerControl";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent != null &&intent.getExtras() != null) {
Bundle bundle = intent.getExtras();
if (!bundle.getString("input_timer").equals(null)) {
String input_timer = bundle.getString("input_timer");
if(input_timer.equals("start")) {// start
startSMSTimer();
}
else if(input_timer.equals("stop")) {// stop
stopSMSTimer();
}
else{}
}
}
finish();
}
public void startSMSTimer(){
if (timer_SMS != null) {
timer_SMS.cancel();
timer_SMS = null;
}
timer_SMS = new CountDownTimer(100000, 20000) {
#Override
public void onTick(long millisUntilFinished) {
long timOver = 100000 - millisUntilFinished;
Log.d(TAG, String.valueOf(timOver));
}
#Override
public void onFinish() { }
};
timer_SMS.start();
}
public void stopSMSTimer(){
if (timer_SMS != null) {
timer_SMS.cancel();
timer_SMS = null;
}
}
}
You need to send "stop" while sending intent for stop as follows :
//In Controller class
//===========Start========
Intent smsTimer = new Intent(getApplicationContext(), TimmerControl.class);
smsTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsTimer.putExtra("input_timer", "start"); // start
getApplicationContext().startActivity(smsTimer);
//===========Stop========
Intent smsTimer = new Intent(getApplicationContext(), TimmerControl.class);
smsTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsTimer.putExtra("input_timer", "stop"); // stop
getApplicationContext().startActivity(smsTimer);
public class TimmerControl extends Service {
CountDownTimer timer_SMS;
private BroadcastReceiver mReceiver;
#Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("start");
intentFilter.addAction("stop");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//extract our message from intent
if (intent.getAction().equals("start")) {
startSMSTimer();
}
if (intent.getAction().equals("stop")) {
stopSMSTimer();
}
}
};
this.registerReceiver(mReceiver, intentFilter);
}
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(this.mReceiver);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void startSMSTimer() {
if (timer_SMS != null) {
timer_SMS.cancel();
timer_SMS = null;
}
timer_SMS = new CountDownTimer(100000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
long timOver = 100000 - millisUntilFinished;
Log.e("Time: ", ""+timOver);
}
#Override
public void onFinish() {
Log.e("finished: ","");
}
};
timer_SMS.start();
}
public void stopSMSTimer() {
if (timer_SMS != null) {
timer_SMS.cancel();
timer_SMS = null;
Log.e("Stop: ","");
}
stopSelf();
}
}
SMSControllerActivity.java
public class SMSControllerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smscontroller);
findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isServiceRunning(TimmerControl.class))
startService(new Intent(SMSControllerActivity.this, TimmerControl.class));
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
sendBroadcast(new Intent("start"));
}
}, 500);
}
});
findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendBroadcast(new Intent("stop"));
}
});
;
}
private boolean isServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
activity_smscontroller.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/btn_start"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Start" />
<Button
android:id="#+id/btn_stop"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Stop" />
</LinearLayout>

How to use ActivityManager.setWatchHeapLimit() to watch heap_limit

According to the official document:
https://developer.android.com/reference/android/app/ActivityManager.html#setWatchHeapLimit(long)
I wrote a demo to see whether the HEAP_LIMIT would be triggered.But seems that it was not working,and here is my code.
public class ActivityManagerActivity extends Activity
{
private String TAG = this.getClass().getName();
private Button btnIncreaseMemory;
private BroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_manager);
registerBroadcast();
registerHeapLimit();
iniComponent();
}
private void iniComponent()
{
btnIncreaseMemory = (Button) findViewById(R.id.btnIncreaseMemory);
btnIncreaseMemory.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Bitmap bitmap = ((BitmapDrawable) getDrawable(R.mipmap.image)).getBitmap();
Log.e(TAG, "bitmap size:" + bitmap.getByteCount());
((ImageView) findViewById(R.id.ivBitmap)).setImageBitmap(bitmap);
}
});
}
#Override
public void onDestroy()
{
super.onDestroy();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.clearWatchHeapLimit();
if (receiver != null)
{
unregisterReceiver(receiver);
receiver = null;
}
}
private void registerHeapLimit()
{
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.setWatchHeapLimit(2);
}
private void registerBroadcast()
{
IntentFilter filter = new IntentFilter();
filter.addAction("ACTION_REPORT_HEAP_LIMIT");
receiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
// not be called
Toast.makeText(ActivityManagerActivity.this, "get msg", Toast.LENGTH_SHORT).show();
}
};
registerReceiver(receiver, filter);
}
}
I change the code to:
public class ActivityManagerActivity extends Activity
{
private String TAG = this.getClass().getName();
private Button btnIncreaseMemory;
private BroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_manager);
registerBroadcast();
registerHeapLimit();
iniComponent();
}
int index = 0;
private void iniComponent()
{
btnIncreaseMemory = (Button) findViewById(R.id.btnIncreaseMemory);
btnIncreaseMemory.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if(index == 0)
{
Bitmap bitmap = ((BitmapDrawable) getDrawable(R.mipmap.img6802)).getBitmap();
Log.e(TAG, "bitmap1 size:" + bitmap.getByteCount());
((ImageView) findViewById(R.id.ivBitmap)).setImageBitmap(bitmap);
index = 1;
}
else if(index == 1)
{
Bitmap bitmap = ((BitmapDrawable) getDrawable(R.mipmap.img6803)).getBitmap();
Log.e(TAG, "bitmap2 size:" + bitmap.getByteCount());
((ImageView) findViewById(R.id.ivBitmap2)).setImageBitmap(bitmap);
index = 2;
}
else if(index == 2)
{
Bitmap bitmap = ((BitmapDrawable) getDrawable(R.mipmap.img6804)).getBitmap();
Log.e(TAG, "bitmap3 size:" + bitmap.getByteCount());
((ImageView) findViewById(R.id.ivBitmap3)).setImageBitmap(bitmap);
index = 3;
}
}
});
}
#Override
public void onDestroy()
{
super.onDestroy();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.clearWatchHeapLimit();
if (receiver != null)
{
unregisterReceiver(receiver);
receiver = null;
}
}
private void registerHeapLimit()
{
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.setWatchHeapLimit(157286400);//150MB
}
private void registerBroadcast()
{
IntentFilter filter = new IntentFilter();
filter.addAction("ACTION_REPORT_HEAP_LIMIT");
receiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
// not be called
Toast.makeText(ActivityManagerActivity.this, "get msg", Toast.LENGTH_SHORT).show();
}
};
registerReceiver(receiver, filter);
}
}
But still no notifies, even the used-heap passed the limit 150MB which I set.
Increase the pss limit to a reasonable value that will be crossed when clicking the button.
The value you provided (2k) is too small, and I believe your activity crosses this value even before you click the button.

How should I reuse the AnymoteClient service, so that I do not have to re-pair with google tv when I launch a new activity?

I am doing some investigations with the GoogleTV and a Android tablet. I have managed to make an android application that can send control messages to the google tv from the main Activity, what I am trying to do is launch a new activity from the main Activity and continue using the AnymoteClientService Service with the new activity. In my main activity I get an anymoteSender handle which I use to send KeyEvent messages to the google tv, how do I transfer this to the new activity (SlidepuzzleActivity)? I could instantiate it all again, but that would mean having to go through the whole pairing process again.
From the code below you will see that I have an anymoteSender in my SlidepuzzleActivity class, this will throw an error, but illustrates where I need to reuse that variable.
Code:
MainActivity.java:
package uk.co.myapp.gtvremote;
//imports removed for paste
public class MainActivity extends Activity implements ClientListener{
private AnymoteSender anymoteSender;
private TextView statusText;
protected AnymoteClientService mAnymoteClientService;
private static String statusPrefix = "Status: ";
private Context mContext;
private ProgressBar progressBar;
private Handler handler;
private TouchHandler touchPadHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.a_progressbar);
progressBar.setVisibility(View.VISIBLE);
mContext = this;
ImageButton upArrowButton = (ImageButton) findViewById(R.id.upArrow);
ImageButton leftArrowButton = (ImageButton) findViewById(R.id.leftArrow);
ImageButton centreButton = (ImageButton) findViewById(R.id.centreButton);
ImageButton rightArrowButton = (ImageButton) findViewById(R.id.rightArrow);
ImageButton downArrowButton = (ImageButton) findViewById(R.id.downArrow);
ImageButton backButton = (ImageButton) findViewById(R.id.backButton);
ImageButton homeButton = (ImageButton) findViewById(R.id.homeButton);
Button testButton = (Button) findViewById(R.id.testButton);
upArrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_UP);
}
});
leftArrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_LEFT);
}
});
centreButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_CENTER);
}
});
rightArrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_RIGHT);
}
});
downArrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_DOWN);
}
});
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_BACK);
}
});
homeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_HOME);
}
});
testButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, SlidepuzzleActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
handler = new Handler();
// Bind to the AnymoteClientService
Intent intent = new Intent(mContext, AnymoteClientService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
statusText = (TextView) findViewById(R.id.statusText);
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
/*
* ServiceConnection listener methods.
*/
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mAnymoteClientService = ((AnymoteClientService.AnymoteClientServiceBinder) service)
.getService();
mAnymoteClientService.attachClientListener(MainActivity.this);
}
#Override
public void onServiceDisconnected(ComponentName name) {
mAnymoteClientService.detachClientListener(MainActivity.this);
mAnymoteClientService = null;
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onConnected(AnymoteSender anymoteSender) {
if (anymoteSender != null) {
// Send events to Google TV using anymoteSender.
// save handle to the anymoteSender instance.
this.anymoteSender = anymoteSender;
attachTouchListnertoTouchPad();
} else {
statusText.setText(statusPrefix + "Connection attempt failed, cant find send handler");
//attempt to connect again?
//attemptToConnect();
}
// Hide the progressBar once connection to Google TV is established. Make the text display appropriately
handler.post(new Runnable() {
public void run() {
progressBar.setVisibility(View.INVISIBLE);
statusText.setText(statusPrefix + "Connected to GoogleTV");
}
});
}
#Override
public void onDisconnected() {
// show message to tell the user about disconnection.
statusText.setText(statusPrefix + "Disconnected");
// Try to connect again if needed. This may be need to be done via button
attemptToConnect();
this.anymoteSender = null;
}
#Override
public void onConnectionError() {
// show message to tell the user about disconnection.
statusText.setText(statusPrefix + "Connection error encountered");
// Try to connect again if needed.
attemptToConnect();
this.anymoteSender = null;
}
#Override
protected void onDestroy() {
if (mAnymoteClientService != null) {
mAnymoteClientService.detachClientListener(this);
}
unbindService(mConnection);
super.onDestroy();
}
private void attachTouchListnertoTouchPad()
{
// Attach touch handler to the touchpad view
touchPadHandler = new TouchHandler(
findViewById(R.id.touchPad), Mode.POINTER_MULTITOUCH, anymoteSender);
}
public void attemptToConnect()
{
//stub to invoke connection attempt
}
private void sendKeyEvent(final int keyEvent) {
// create new Thread to avoid network operations on UI Thread
if (anymoteSender == null) {
Toast.makeText(MainActivity.this, "Waiting for connection",
Toast.LENGTH_LONG).show();
return;
}
anymoteSender.sendKeyPress(keyEvent);
}
}
SlidepuzzleActivity.java:
package uk.co.myapp.gtvremote;
//imports removed for paste
public class SlidepuzzleActivity extends Activity implements ClientListener{
private AnymoteClientService mAnymoteClientService;
private Context mContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slidepuzzle);
mContext = this;
ImageButton piece1x1 = (ImageButton) findViewById(R.id.piece1x1);
ImageButton piece1x2 = (ImageButton) findViewById(R.id.piece1x2);
ImageButton piece1x3 = (ImageButton) findViewById(R.id.piece1x3);
ImageButton piece2x1 = (ImageButton) findViewById(R.id.piece2x1);
ImageButton piece2x2 = (ImageButton) findViewById(R.id.piece2x2);
ImageButton piece2x3 = (ImageButton) findViewById(R.id.piece2x3);
ImageButton piece3x1 = (ImageButton) findViewById(R.id.piece3x1);
ImageButton piece3x2 = (ImageButton) findViewById(R.id.piece3x2);
ImageButton piece3x3 = (ImageButton) findViewById(R.id.piece3x3);
Intent intent = new Intent(mContext, AnymoteClientService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
piece1x1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private ServiceConnection mConnection = new ServiceConnection() {
/*
* ServiceConnection listener methods.
*/
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mAnymoteClientService = ((AnymoteClientService.AnymoteClientServiceBinder) service)
.getService();
mAnymoteClientService.attachClientListener(SlidepuzzleActivity.this);
}
#Override
public void onServiceDisconnected(ComponentName name) {
mAnymoteClientService.detachClientListener(SlidepuzzleActivity.this);
mAnymoteClientService = null;
}
};
private void sendKeyEvent(final int keyEvent) {
// create new Thread to avoid network operations on UI Thread
if (anymoteSender == null) {
Toast.makeText(SlidepuzzleActivity.this, "Waiting for connection",
Toast.LENGTH_LONG).show();
return;
}
anymoteSender.sendKeyPress(keyEvent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.slidepuzzle, menu);
return true;
}
#Override
public void onConnected(AnymoteSender anymoteSender) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onConnectionError() {
// TODO Auto-generated method stub
}
#Override
protected void onDestroy() {
if (mAnymoteClientService != null) {
mAnymoteClientService.detachClientListener(this);
}
unbindService(mConnection);
super.onDestroy();
}
}
Just published an update to AnymoteLibrary for this.
In your MainActivity call both bindService() (already) and startService() for AnymoteClientService. The reason behind calling startService() is to keep the service and its anymoteSender instance around so that other Activitys in the same app can use it.
In the second Activity, implement ClientListener ( if you want to get onDisconnected() callback) and bind to the service and attachClientListener(). To get the AnymoteSender instance, call AnymoteClientService.getAnymoteSender(). Note that it can return null if the connection to Google TV is lost.
When all Activitys are done using AnymoteSender, remember to call stopService() for AnymoteClientService.

Categories

Resources