I am developing an app where I am using android's dialog for granting dangerous permissions. And when I click button for login on LoginActivity I go to Main activity and dialog is show. But when I press BACK button, again this dialog appears! This is my MainActivity(Just to say that my launcher activity is MAinActivity, not LoginActivity):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_main);
Bugsnag.init(this, BUGSNAG_API_KEY);
company_name = (TextView) findViewById(R.id.company_name);
aUsername = (TextView) findViewById(R.id.username);
company_name.setTextColor(ContextCompat.getColor(this, R.color.colorBlue));
// aUsername.setTextColor(ContextCompat.getColor(this, R.color.colorBlack));
toolbarImage = (ImageView) findViewById(R.id.image_id);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
getDataForToolbar();
checkIfServiceWorking();
askingForPermissionInManifest();
alertForEnablingGPS();
logoutWhenCompanyDisabled();
String token = FirebaseInstanceId.getInstance().getToken();
Log.d("FCM", "Fire_base token is: " + token);
readTokenFromSharedPreferences();
initializeInjectorListIcons();
initializeListIcons();
initializeInjector();
initialize();
BottomBar bottomBar = (BottomBar) findViewById(R.id.bottomBar);
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
getFragment(tabId);
}
});
}
public static Context getContx() {
return mContext;
}
private void checkIfServiceWorking() {
mLocationService = new LocationService(getContx());
mServiceIntent = new Intent(getContx(), mLocationService.getClass());
if (!isMyServiceRunning(LocationService.class)){
startService(mServiceIntent);
}
}
private boolean isMyServiceRunning(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())) {
Log.i ("isMyServiceRunning?", true + "");
return true;
}
}
Log.i ("isMyServiceRunning?", false + "");
return false;
}
private void initializeInjector() {
this.accountComponent = DaggerAccountComponent.builder()
.applicationComponent(getApplicationComponent())
.activityModule(getActivityModule())
.accountModule(new AccountModule())
.build();
}
public void initialize() {
this.getComponent(AccountComponent.class).inject(this);
this.accountPresenter.setView(this);
this.accountPresenter.initialize();
}
public void initializeInjectorListIcons() {
this.accountComponent = DaggerAccountComponent.builder()
.applicationComponent(getApplicationComponent())
.activityModule(getActivityModule())
.listIconsModule(new ListIconsModule())
.build();
}
public void initializeListIcons() {
this.getComponent(AccountComponent.class).inject(this);
this.listIconsPresenter.initializeListIcons();
}
#Override
public AccountComponent getComponent() {
return accountComponent;
}
#Override
public void viewAccount(AccountModel accountModel) {
if (accountModel != null) {
if (accountModel.getRoles().getName().equals(getResources().getString(R.string.role_team_leader)) || (accountModel.getRoles().getName().equals(getResources().getString(R.string.role_user)))){
Gson account_json = new Gson();
String account = account_json.toJson(accountModel);
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.Account_json), MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(getResources().getString(R.string.account_json), account);
editor.apply();
List<ButtonModel> arrayListButton = accountModel.getLayout().getButtons();
if (accountModel.getRoles().getName().equals(getResources().getString(R.string.role_user)) || accountModel.getRoles().getName().equals(getResources().getString(R.string.role_team_leader)) && arrayListButton.size() != 0) {
showLanguageSettings();
addFragment(R.id.fragment_container, new DashboardFragment());
goingToFragmentWithNotificationClick();
FirebaseMessaging.getInstance().subscribeToTopic(accountModel.getUuid());
for (CompanyModel com : accountModel.getCompanies()) {
String teamUuid = com.getTeam().getUuid();
String language = com.getLanguage().getCode();
SharedPreferences sharedPreferences1 = getSharedPreferences("language", MODE_PRIVATE);
SharedPreferences.Editor editor1 = sharedPreferences1.edit();
editor1.putString("prefLanguage", language);
editor1.apply();
if (teamUuid != null) {
FirebaseMessaging.getInstance().subscribeToTopic(teamUuid);
}
}
FirebaseMessaging.getInstance().subscribeToTopic(accountModel.getRoles().getUuid());
} else if (arrayListButton.size() == 0 && accountModel.getRoles().getName().equals(getResources().getString(R.string.role_user)) || accountModel.getRoles().getName().equals(getResources().getString(R.string.role_team_leader))) {
addFragment(R.id.fragment_container, new EmptyListButtonFragment());
}
getDataForToolbar();
}
else {
removeTokenAndWrongAccountFromSharedPreferences();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_log_out) {
if (isNetworkConnected()) {
unsubscribingFromFirebase();
removeTokenAndAccountFromSharedPreferences();
shouldRestart = false;
stopService(mServiceIntent);
Log.i("MAIN_ACTIVITY", "Logout!");
Log.d("MAIN_ACTIVITY " , "Internet access ");
}
else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.need_internet), Toast.LENGTH_SHORT).show();
}
}
if (id == R.id.action_fcmToken) {
TextView textView = new TextView(this);
textView.setHeight(300);
textView.setText(FirebaseInstanceId.getInstance().getToken());
textView.setTextIsSelectable(true);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Token");
builder.setView(textView)
.setCancelable(true)
.show();
}
if (id == R.id.versionInfo) {
getCurrentAppVersionInfo();
}
if (id == R.id.LocationInfo){
getLocationInfo();
}
return super.onOptionsItemSelected(item);
}
public void readTokenFromSharedPreferences() {
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.token_preferences), MODE_PRIVATE);
final String strPref = sharedPreferences.getString(getResources().getString(R.string.token), null);
if (strPref == null) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
public void removeTokenAndAccountFromSharedPreferences() {
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.token_preferences), MODE_PRIVATE);
sharedPreferences.edit().remove(getResources().getString(R.string.token)).apply();
final String strPref = sharedPreferences.getString(getResources().getString(R.string.token), null);
SharedPreferences sharedPreferencesAccount = getSharedPreferences(getResources().getString(R.string.Account_json), MODE_PRIVATE);
sharedPreferencesAccount.edit().remove(getResources().getString(R.string.account_json)).apply();
final String accountPref = sharedPreferencesAccount.getString(getResources().getString(R.string.account_json), null);
if (strPref == null && accountPref == null) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
public void removeTokenAndWrongAccountFromSharedPreferences() {
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.token_preferences), MODE_PRIVATE);
String strPref;
strPref = sharedPreferences.getString(getResources().getString(R.string.token), null);
SharedPreferences sharedPreferencesAccount = getSharedPreferences(getResources().getString(R.string.Account_json), MODE_PRIVATE);
String accountPref;
accountPref=sharedPreferencesAccount.getString(getResources().getString(R.string.account_json), null);
if(strPref != null || accountPref != null){
sharedPreferences.edit().remove(getResources().getString(R.string.token)).apply();
sharedPreferencesAccount.edit().remove(getResources().getString(R.string.account_json)).apply();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
Toast.makeText(MainActivity.this, getResources().getString(R.string.message_for_roles), Toast.LENGTH_LONG).show();
}
}
public void getFragment(int id) {
switch (id) {
case R.id.tab_menu_dashboard:
addFragment(R.id.fragment_container, new DashboardFragment());
break;
case R.id.tab_menu_messages:
addFragment(R.id.fragment_container, new MessagesFragment());
break;
case R.id.tab_menu_team:
addFragment(R.id.fragment_container, new TeamFragment());
break;
case R.id.tab_menu_incidents:
addFragment(R.id.fragment_container, new IncidentsFragment());
break;
}
}
#Override
protected void onResume() {
readTokenFromSharedPreferences();
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (alertDialog != null) {
alertDialog.dismiss();
}
}
#Override
protected void onPause() {
super.onPause();
if (alertDialog != null) {
alertDialog.dismiss();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
stopService(mServiceIntent);
Log.i("MAIN_ACTIVITY", "onDestroy!");
}
public void goingToFragmentWithNotificationClick() {
String clickNotification = getIntent().getStringExtra("notification_type");
String clickReportActivity = getIntent().getStringExtra("report_activity");
if (clickNotification != null) {
if (mAccount != null) {
if (mAccount.getRoles().getName().equals(getResources().getString(R.string.role_team_leader))) {
if (clickNotification.equals("incident_notify")) {
addFragment(R.id.fragment_container, new IncidentsFragment());
} else if (clickNotification.equals("chat_message")) {
addFragment(R.id.fragment_container, new MessagesFragment());
}
} else {
if (clickNotification.equals("chat_message")) {
addFragment(R.id.fragment_container, new MessagesFragment());
}
}
}
}
if(clickReportActivity!=null){
addFragment(R.id.fragment_container, new IncidentsFragment());
}
}
public void picassoLoader(Context context, ImageView imageView, String url) {
Picasso.with(context)
.load(url)
.resize(70, 58)
.transform(new RoundedTransformation(8, 0))
.into(imageView);
}
private void getCurrentAppVersionInfo() {
int versionCode = -1;
String versionName = "";
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
versionCode = packageInfo.versionCode;
versionName = packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String alert1 = "Version Code: " + versionCode;
String alert2 = "Version Name: " + versionName;
builder.setMessage(alert1 + "\n" + alert2).show();
}
#SuppressLint("SetTextI18n")
public void getDataForToolbar() {
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.Account_json), Context.MODE_PRIVATE);
final String account = sharedPreferences.getString(getResources().getString(R.string.account_json), null);
if (account != null) {
Gson gson = new Gson();
mAccount = gson.fromJson(account, AccountModel.class);
for (CompanyModel com : mAccount.getCompanies()) {
String name = com.getName();
company_name.setText(name);
logo_url = com.getLogo_url();
}
if (logo_url == null || logo_url.isEmpty()) {
Picasso
.with(this)
.load(R.drawable.default_company)
.resize(70, 58)
.transform(new RoundedTransformation(8, 0))
.into(toolbarImage);
} else {
picassoLoader(this, toolbarImage, logo_url);
}
String username = mAccount.getUsername();
if(mAccount.getStatus()){
aUsername.setText(username + "/" + getResources().getString(R.string.on_duty));
aUsername.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorGreen));
}else{
aUsername.setText(username + "/" + getResources().getString(R.string.off_duty));
aUsername.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorWhite));
}
}
}
public void alertForEnablingGPS() {
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(getResources().getString(R.string.enable_location_Service));
builder.setMessage(getResources().getString(R.string.GPS));
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
}
public void logoutWhenCompanyDisabled() {
String logout = getIntent().getStringExtra("notification_type");
if (logout != null) {
if (logout.equals("company_disabled")) {
unsubscribingFromFirebase();
removeTokenAndAccountFromSharedPreferences();
}
}
}
public void unsubscribingFromFirebase() {
if (mAccount != null) {
if (mAccount.getRoles().getName().equals(getResources().getString(R.string.role_user)) || mAccount.getRoles().getName().equals(getResources().getString(R.string.role_team_leader))) {
FirebaseMessaging.getInstance().unsubscribeFromTopic(mAccount.getUuid());
FirebaseMessaging.getInstance().unsubscribeFromTopic(mAccount.getRoles().getUuid());
for (CompanyModel com : mAccount.getCompanies()) {
String teamUuid = com.getTeam().getUuid();
if (teamUuid != null) {
FirebaseMessaging.getInstance().unsubscribeFromTopic(teamUuid);
}
Log.d("FCM", "UnSubscribed on team Uuid: " + teamUuid);
}
}
}
}
public class RoundedTransformation implements com.squareup.picasso.Transformation {
private final int radius;
private final int margin;
public RoundedTransformation(final int radius, final int margin) {
this.radius = radius;
this.margin = margin;
}
#Override
public Bitmap transform(final Bitmap source) {
final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
canvas.drawRoundRect(new RectF(margin, margin, source.getWidth() - margin, source.getHeight() - margin), radius, radius, paint);
if (source != output) {
source.recycle();
}
return output;
}
#Override
public String key() {
return "rounded";
}
}
private boolean isNetworkConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
public void askingForPermissionInManifest(){
if((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) != PackageManager.PERMISSION_GRANTED){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){
}else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS, Manifest.permission.CALL_PHONE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("all", "good");
alertForEnablingGPS();
restartActivity();
} else {
Log.d("need location", "need permissions");
}
break;
}
}
}
This is LogIn activity:
public class LoginActivity extends BaseActivity implements HasComponent<LoginComponent>, TokenView {
Credentials credentials;
TextInputEditText username;
TextInputEditText password;
Button login;
Configuration config;
private LoginComponent loginComponent;
#Inject LoginPresenter loginPresenter;
static Context mContext;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
checkLanguage();
username = (TextInputEditText)findViewById(R.id.username);
password = (TextInputEditText)findViewById(R.id.password);
credentials = new Credentials();
login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getUsername = username.getText().toString();
String getPassword = password.getText().toString();
if (getUsername.length()>0 && getPassword.length()>0 ) {
credentials.setUsername(getUsername);
credentials.setPassword(getPassword);
allOperations();
} else {
Toast.makeText(LoginActivity.this, R.string.empty_fields , Toast.LENGTH_LONG).show();
}
}
});
}
private void initializeInjector() {
this.loginComponent = DaggerLoginComponent.builder()
.applicationComponent(getApplicationComponent())
.activityModule(getActivityModule())
.loginModule(new LoginModule(this.credentials))
.build();
}
public void initialize () {
this.getComponent(LoginComponent.class).inject(this);
this.loginPresenter.setView(this);
this.loginPresenter.initialize(this.credentials);
}
#Override
public void viewToken(TokenModel tokenModel) {
if (tokenModel != null) {
String tokMod = tokenModel.getToken();
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.token_preferences), MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(getResources().getString(R.string.token), tokMod);
editor.apply();
Log.d("Token na logovanju je: ", "TokenLogo" + tokMod);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
public void allOperations () {
initializeInjector();
initialize();
}
#Override
public LoginComponent getComponent() {
return loginComponent;
}
#Override
public void showLoading() {
}
#Override
public void hideLoading() {
}
#Override
public void showRetry() {
}
#Override
public void hideRetry() {
}
#Override
public void showError(int message) {
Toast.makeText(LoginActivity.this, message , Toast.LENGTH_LONG).show();
}
#Override
public Context context() {
return null;
}
#Override public void onDestroy() {
super.onDestroy();
if (loginPresenter != null) {
this.loginPresenter.destroy();
}
}
public void checkLanguage(){
SharedPreferences sharedPreferences = getSharedPreferences("language", MODE_PRIVATE);
String language = sharedPreferences.getString("prefLanguage", null);
config = new Configuration(getResources().getConfiguration());
if(language!=null){
if(language.equals("en")){
config.locale = Locale.ENGLISH;
}
if(language.equals("sr")){
config.locale = new Locale("sr");
}
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
onConfigurationChanged(config);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public static void downloadFile(String uRl, String name_image) {
File direct = new File(Environment.getExternalStorageDirectory() + "/icons");
if (!direct.exists()) {
direct.mkdirs();
}
DownloadManager mgr = (DownloadManager)mContext.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Incident icons for dashboard.")
.setDestinationInExternalPublicDir("/icons", name_image);
mgr.enqueue(request);
}}
Could anyone helps me how to fix this problem, how to get this dialog only when I login into Main activity, not when I click BACK button? Thanks in advance.
Related
I have created a timer that starts timing on a handleClick() and continues timing throughout the app. When I return to the firstActivity I would like the timer to stop in the onResume(). however whenever I return to the firstActivity I get the following error below. How do I solve this?
Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.warrenedy.julyfinal.TimeTracker2.isTracking()' on a null object reference
Code Below
#Override
protected void onResume() {
super.onResume();
prepareActivityTextsAndButtons();
prepareTimingButtons();
mTimeTracker2.stopTracker();
Toast.makeText(this, "Onresume call", Toast.LENGTH_SHORT).show();
}
public void handleClick(View v) {
if (DBG) Log.d(LOG_TAG, "handleClick()..");
if (!mServiceBound) return;
switch (v.getId()) {
case R.id.button_activity_start_stop:
onActivityButtonClick(v);
break;
}
}
private void onActivityButtonClick(View v) {
if (DBG)
Log.d(LOG_TAG, "onMeditateButtonClick().. tracking " + mTimeTracker2.isTracking());
ToggleButton button = (ToggleButton) v;
if (mTimeTracker2.isTracking()) {
if (mCurrentTrackingActivity == null) return;
if (button == mButtonActivityTimers[mCurrentTrackingActivity.ordinal()]) {
mTimeTracker2.stopTracker();
Utils2.playStopAudio(getApplicationContext());
// button.setText(R.string.str_start);
mCurrentTime.setText(Utils2.secToString(0));
button.setChecked(false);
}
}
}
Code Continued
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DBG) Log.d(LOG_TAG, "onCreate()..");
setContentView(R.layout.activity_meditation_tracker);
getSupportActionBar().hide();
mContext = getApplicationContext();
mSharedpreferences = getSharedPreferences(Utils.MyPREFERENCES, Context.MODE_PRIVATE);
exercise_star = sharedpreferences.getInt("exercise_star", 0);
meditation_star = sharedpreferences.getInt("meditation_star", 0);
study_star = sharedpreferences.getInt("study_star", 0);
isAlarmSet = sharedpreferences.getBoolean("isAlarmSet", false);
/* Retrieve a PendingIntent that will perform a broadcast */
mActivity = MeditationTrackerActivity.this;
mButtonSavePoints = (Button) findViewById(R.id.btn_save_points);
mButtonRestorePoints = (Button) findViewById(R.id.btn_restore_points);
btnHelpBut = (Button) findViewById(R.id.btnHelp);
ACTIVITY_NAMES = getResources().getStringArray(R.array.activity_names);
mCurrentTime = (TextView) findViewById(R.id.tv_current_time);
mCurrentTime.setText(Utils2.secToString(0));
if (!isAlarmSet) {
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putBoolean("isAlarmSet", true);
ed.commit();
startAlarmService();
}
isAuthenticated = sharedpreferences.getBoolean("isAuth", true);
if (Build.VERSION.SDK_INT < 23) {
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
} else {
insertPermissionWrapper();
}
}
### StartAlarmService
public void startAlarmService() {
Intent alarmIntent = new Intent(MeditationTrackerActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MeditationTrackerActivity.this, 0, alarmIntent, 0);
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR_OF_DAY, 23); // At the hour you wanna fire
firingCal.set(Calendar.MINUTE, 45); // Particular minute
firingCal.set(Calendar.SECOND, 0); // particular second
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if (intendedTime >= currentTime) {
mAlarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
} else {
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
mAlarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
}
Toast.makeText(this, "Main Alarm Set", Toast.LENGTH_SHORT).show();
}
### CancelAlarm
public void cancelAlarmService() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
### StartService
private void startService() {
Intent serIntent = new Intent(this, TimeTrackingService2.class);
startService(serIntent);
bindService(serIntent, mServiceConnection, BIND_AUTO_CREATE);
}
### UpdateCurrentTime
private void updateCurrentTime() {
Date date = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
mCurrentTime.setText(sdf.format(date));
}
### ClientAuthenticationFromServer
private void clientAuthenticationFromServer() {
if (Utils2.getConnectivityStatus(mContext)) {
new Auth(mContext, mActivity).execute(Utils2.URL_VALIDATE_CLIENT);
} else {
Utils2.alertPopup(mContext, "You are not connected to internet.kindly connect with internet and try again.The internet is needed only first time for the authentication of client.After authentication no need of internet.", mActivity);
}
}
###Task Complete
#Override
public void onTaskComplete(boolean result) {
if (!result) {
Utils2.alertPopup(mContext, "You are not a valid client.Contact with the owner of the App.", mActivity);
return;
} else {
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putBoolean("isAuth", true);
ed.commit();
startService();
}
}
### OnStart
#Override
protected void onStart() {
super.onStart();
// updateCurrentTime();
// IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
// registerReceiver(mTimeTickReceiver, filter);
}
###OnStop
#Override
protected void onStop() {
super.onStop();
// unregisterReceiver(mTimeTickReceiver);
}
### onDestroy
#Override
protected void onDestroy() {
super.onDestroy();
if (mServiceBound) {
unbindService(mServiceConnection);
}
}
### onTimeButtonClick
private void onTimeButtonClick(View v) {
if (DBG) Log.d(LOG_TAG, "onClick() timebutton.. tracking" + mTimeTracker2.isTracking());
ToggleButton button = (ToggleButton) v;
if (DBG) Log.d(LOG_TAG, "onClick() timebutton.. checked ? " + button.isChecked());
if (mTimeTracker2.isTracking()) {
showStopToast();
Utils2.playStopAudio(getApplicationContext());
button.setChecked(false);
return;
} else {
Utils2.playStartAudio(getApplicationContext());
if (button.isChecked()) {
if (mCurrentCheckedButton != null) mCurrentCheckedButton.setChecked(false);
int time = (Integer) v.getTag();
mCountDownSecs = time;
mCurrentCheckedButton = button;
} else {
mCountDownSecs = 0;
mCurrentCheckedButton = null;
}
}
}
###ShowStopToast
private void showStopToast() {
Toast.makeText(this, "Please stop running activity..", Toast.LENGTH_SHORT).show();
}
### onTimerProgress
#Override
public void onTimerProgress(int sec, ACTIVITIES activity) {
if (mCurrentTrackingActivity == null) {
mCurrentTrackingActivity = activity;
}
mCurrentTime.setText(Utils2.secToString(sec));
if (activity == ACTIVITIES.STUDY) {
if (sec == 3600) {
mTimeTracker2.stopTracker();
}
}
}
### onTimerFinish
#Override
public void onTimerFinish(int end, ACTIVITIES activity) {
mCurrentTime.setText(Utils2.secToString(end));
mButtonActivityTimers[activity.ordinal()].setChecked(false);
mCurrentTrackingActivity = null;
Utils2.playStopAudio(getApplicationContext());
}
private void prepareActivityTextsAndButtons() {
for (int i = 0; i < ACTIVITY_COUNT; i++) {
View parent = findViewById(ACTIVITY_LAYOUT_IDS[i]);
mTextActivityNames[i] = (TextView) parent.findViewById(R.id.tv_activity_name);
mTextActivityNames[i].setText(ACTIVITY_NAMES[i]);
//mTextActivityTimers[i] = (TextView) parent.findViewById(R.id.tv_timer_progress);
mRatingBars[i] = (RatingBar) parent.findViewById(R.id.ratingBar);
mButtonActivityTimers[i] = (ToggleButton) parent.findViewById(R.id.button_activity_start_stop);
mButtonActivityTimers[i].setText(null);
mButtonActivityTimers[i].setTextOn(null);
mButtonActivityTimers[i].setTextOff(null);
mButtonActivityTimers[i].setTag(ACTIVITIES.values()[i]);
}
}
private void prepareTimingButtons() {
mTimingButtons = new ToggleButton[7];
mTimingButtons[0] = (ToggleButton) findViewById(R.id.button_timer_0);
addTextToTimingButtons(5, mTimingButtons[0]);
}
private void addTextToTimingButtons(int min, Button button) {
// button.setText(min + " " + getString(R.string.str_min));
button.setTag(min * 60);
}
public void onCustomTimeStarted(int secs) {
if (DBG) Log.d(LOG_TAG, "onCustomTimeStarted : secs " + secs);
if (mTimeTracker2.isTracking()) {
showStopToast();
} else {
int oneday = 24 * 3600;
if (secs > oneday) {
Toast.makeText(this, "Adjusted to 24 hrs", Toast.LENGTH_SHORT).show();
secs = oneday;
} else if (secs < 60) {
Toast.makeText(this, "Should be at least a minute.", Toast.LENGTH_SHORT).show();
return;
}
mTimingButtons[6].setChecked(true);
mTimingButtons[6].setTag(secs);
onTimeButtonClick(mTimingButtons[6]);
//mTimeTracker2.startTracker(secs, this);
//mButtonMeditate.setText(R.string.meditate_stop);
}
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
}
return true;
}
private void insertPermissionWrapper() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.READ_PHONE_STATE))
permissionsNeeded.add("READ_PHONE_STATE");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
}
});
return;
}
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
return;
} else {
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
}
// insertDummyContact();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.app.AlertDialog.Builder(MeditationTrackerActivity.this)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
) {
// All Permissions Granted
if (!isAuthenticated) {
clientAuthenticationFromServer();
} else {
startService();
}
} else {
// Permission Denied
Toast.makeText(MeditationTrackerActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
finish();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void setBootReceiverEnabled(int componentEnabledState) {
ComponentName componentName = new ComponentName(this, DeviceBootReceiver.class);
PackageManager packageManager = getPackageManager();
packageManager.setComponentEnabledSetting(componentName,
componentEnabledState,
PackageManager.DONT_KILL_APP);
};
TimeTracker2.class
public class TimeTracker2 {
private static final int MSG_TRACKER_STOPPED = 1;
private static final int MSG_TRACKER_PROGRESS_UPDATE = 2;
private Context mContext;
private boolean mIsTrackingInProgress;
private TrackerServiceCallback mServiceCallback;
private TimerProgressCallback2 mProgressCallback;
private Timer mTimer = new Timer();
private TimerHandler mTimerHandler = new TimerHandler();
private TimerTask mIncrementTask, mDecrementTask;
private int mCounter;
private int mMaxCounter;
private MeditationTrackerActivity.ACTIVITIES mCurrentTrackingActivity;
private class IncrementTask extends TimerTask {
IncrementTask() {
mCounter = 0;
}
#Override
public void run() {
mCounter++;
mTimerHandler.sendEmptyMessage(MSG_TRACKER_PROGRESS_UPDATE);
}
}
private class DecrementTask extends TimerTask {
DecrementTask(int sec) {
mCounter = sec;
}
#Override
public void run() {
if (mCounter == 0) {
ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
toneGenerator.startTone(ToneGenerator.TONE_CDMA_PIP, 500);
cancel();
mTimerHandler.sendEmptyMessage(MSG_TRACKER_STOPPED);
return;
}
mCounter --;
mTimerHandler.sendEmptyMessage(MSG_TRACKER_PROGRESS_UPDATE);
}
}
public interface TimerProgressCallback2 {
void onTimerProgress(int sec, MeditationTrackerActivity.ACTIVITIES activity);
void onTimerFinish(int end, MeditationTrackerActivity.ACTIVITIES activity);
}
public TimeTracker2(Context context, TrackerServiceCallback serviceCallback) {
mContext = context;
mServiceCallback = serviceCallback;
}
public void startTracker(int time_secs, TimerProgressCallback2 callback, MeditationTrackerActivity.ACTIVITIES activity) {
if (mIsTrackingInProgress) {
Log.i(LOG_TAG, "startTracker().. inProgress!!");
return;
}
mMaxCounter = time_secs;
mProgressCallback = callback;
mIsTrackingInProgress = true;
mServiceCallback.onTrackerStarted(true);
mDecrementTask = new DecrementTask(time_secs);
mTimer.scheduleAtFixedRate(mDecrementTask, 0, 1000);
mCurrentTrackingActivity = activity;
}
public void startTracker(TimerProgressCallback2 callback, MeditationTrackerActivity.ACTIVITIES activity) {
if (mIsTrackingInProgress) {
Log.i(LOG_TAG, "startTracker().. inProgress!!");
return;
}
mMaxCounter = 0;
mProgressCallback = callback;
mIsTrackingInProgress = true;
mServiceCallback.onTrackerStarted(true);
mIncrementTask = new IncrementTask();
mTimer.scheduleAtFixedRate(mIncrementTask, 0, 1000);
mCurrentTrackingActivity = activity;
}
public void setTimerProgressCallback(TimerProgressCallback2 callback) {
if (!mIsTrackingInProgress) return;
mProgressCallback = callback;
}
public void removeTimerProgressCallback() {
mProgressCallback = null;
}
public void stopTracker() {
if (!mIsTrackingInProgress) {
Log.i(LOG_TAG, "stopTracker().. Tracker NOT started!!");
return;
}
mIsTrackingInProgress = false;
mServiceCallback.onTrackerStarted(false);
if (mProgressCallback != null) mProgressCallback.onTimerFinish(mCounter, mCurrentTrackingActivity);
mProgressCallback = null;
if (mIncrementTask != null) mIncrementTask.cancel();
if (mDecrementTask != null) mDecrementTask.cancel();
updateDb();
mCurrentTrackingActivity = null;
}
public boolean isTracking() {
return mIsTrackingInProgress;
}
public MeditationTrackerActivity.ACTIVITIES getCurrentTrackingActivity() {
return mCurrentTrackingActivity;
}
private class TimerHandler extends Handler {
#Override
public void handleMessage(Message msg) {
if (DBG) Log.d(LOG_TAG, "handleMessage()..");
switch (msg.what) {
case MSG_TRACKER_PROGRESS_UPDATE:
if (mProgressCallback != null) mProgressCallback.onTimerProgress(mCounter, mCurrentTrackingActivity);
break;
case MSG_TRACKER_STOPPED:
default:
stopTracker();
break;
}
}
}
private void updateDb() {
final int secs = mMaxCounter > 0 ? mMaxCounter - mCounter : mCounter;
final MeditationTrackerActivity.ACTIVITIES activity = mCurrentTrackingActivity;
AsyncTask.execute(new Runnable() {
#Override
public void run() {
TrackerDb3.insertOrUpdateMeditation(mContext, secs, activity);
}
});
}
}
As screen height of samsung s8 is quite large.My images in LoginUI(attached) were looking small.I calculated phone's height in dp programmatically.
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
Log.d("checkheightdp",dpHeight+"");
It gave me dpheight 692.So,I create a separate layout-h692dp and put my layout with increased image height.For some reason,It is still picking the default layout and hence image not expanding.
My code:
public class LoginActivity extends AppCompatActivity {
private EditText email, psd;
public ImageView deleteEmail;
public ImageView deletePsd;
public ImageView contactUs;
GlobalProvider globalProvider;
private int a = 0;
private Button sign_in_button, tourist_in_button;
private List<String> history = new ArrayList<String>();
private String usernameStr, newVersion = "x";
public static String character = "character";
private ConnectivityManager mConnectivityManager;
private NetworkInfo netInfo;
private ProgressDialog dialog;
public Thread thread;
private BroadcastReceiver myNetReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = mConnectivityManager.getActiveNetworkInfo();
if (netInfo == null) {
Toast.makeText(LoginActivity.this, "网络链接不可用!", Toast.LENGTH_SHORT).show();
}
}
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
globalProvider = GlobalProvider.getInstance(LoginActivity.this);
IntentFilter mFilter = new IntentFilter();
mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(myNetReceiver, mFilter);
//找到对象email、psd、sign_in_button并绑定监听事件
email = (EditText) findViewById(R.id.email);
psd = (EditText) findViewById(R.id.psd);
contactUs = (ImageView) findViewById(R.id.contact_us);
sign_in_button = (Button) findViewById(R.id.sign_in_button);
tourist_in_button = (Button) findViewById(R.id.tourist_in_button);
deleteEmail = (ImageView) findViewById(R.id.deleteEmail);
deletePsd = (ImageView) findViewById(R.id.deletePsd);
// gview=(GridView) findViewById(R.id.grid_layout);
// ImageAdapter imgAdapter=new ImageAdapter(LoginActivity.this);
//gview.setAdapter(imgAdapter);
contactUs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, ContactActivity.class);
startActivity(intent);
}
});
deleteEmail.setVisibility(View.GONE);
deletePsd.setVisibility(View.GONE);
try {
findHistoryList();
} catch (IOException e) {
e.printStackTrace();
}
email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
deleteEmail.setVisibility(View.VISIBLE);
} else {
deleteEmail.setVisibility(View.GONE);
}
}
});
psd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
deletePsd.setVisibility(View.VISIBLE);
} else {
deletePsd.setVisibility(View.GONE);
}
}
});
deleteEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
email.setText("");
}
});
deletePsd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
psd.setText("");
}
});
sign_in_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (email.getText() == null || email.getText().toString().equals("") || psd.getText() == null || email.getText().toString().equals("")) {
new AlertDialog.Builder(LoginActivity.this)
.setMessage(getString(R.string.notempty))
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
} else {
try {
setHistoryList();
} catch (IOException e) {
e.printStackTrace();
}
dialog = new ProgressDialog(LoginActivity.this);
dialog.setMessage(getString(R.string.loging));
dialog.show();
sign_in_button.setEnabled(false);
loginAction(v);
}
}
});
//为sign_in_button绑定监听事件,调用loginAction(v)
tourist_in_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog = new ProgressDialog(LoginActivity.this);
dialog.setMessage(getString(R.string.loging));
dialog.show();
sign_in_button.setEnabled(false);
loginActionTourist(v);
}
});
}
public static void setCharacter(Context context, String cha) {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString(character, cha);
editor.commit();
}
public static String getToken(Context context) {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
String cha = settings.getString(character, ""/*default value is ""*/);
//Log.v("err", tokenStr);
return cha;
}
//创建loginAction()方法
public void loginAction(View view) {
//分别把email、psd的值传递给usernameStr、passwordStr
final String usernameStr = email.getText().toString();
String passwordStr = psd.getText().toString();
Log.d("checkentries",usernameStr+" "+passwordStr);
setCharacter(this, "user");
// Log.d("chkpassword",passwordStr);
//GlobalProvider.getInstance().character =
Map<String, String> params = new HashMap<>();
params.put("password", passwordStr);
params.put("email",usernameStr );
CustomRequest jsonObjectRequest = new CustomRequest(Request.Method.POST, loginUrlStr, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("responsevolley", response.getString("token"));
dialog.dismiss();
globalProvider.IsLoging = true;
sign_in_button.setEnabled(true);
String token;
token = response.getString("token");
token = token.replaceAll("\"", "");//把token中的"\""全部替换成""
Constants.setToken(LoginActivity.this, token);
globalProvider.isLogined=true;
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("isLogin", usernameStr);
startActivity(intent);
//this.setResult(Activity.RESULT_OK);//为结果绑定Activity.RESULT_OK
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("errorvolley", error.toString());
dialog.dismiss();
new AlertDialog.Builder(LoginActivity.this)
.setMessage(getString(R.string.errorId))
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
sign_in_button.setEnabled(true);
}
});
globalProvider.addRequest(jsonObjectRequest);
}
public void loginActionTourist(View view) {
usernameStr = "guest#veg.com";
String passwordStr = "12345678";
setCharacter(this, "tourist");
globalProvider.isLogined = true;
// GlobalProvider.getInstance().character = "tourist";
// 绑定参数
Map<String,String> params = new HashMap();
params.put("email", usernameStr);
params.put("password", passwordStr);
CustomRequest customRequest=new CustomRequest(Request.Method.POST, loginUrlStr, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
dialog.dismiss();
globalProvider.IsLoging = true;
tourist_in_button.setEnabled(true);
String token;
try {
token = response.getString("token");
token = token.replaceAll("\"", "");
Constants.setToken(LoginActivity.this, token);
} catch (JSONException e) {
e.printStackTrace();
}
//把token中的"\""全部替换成""
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("isLogin", usernameStr);
startActivity(intent);
//this.setResult(Activity.RESULT_OK);//为结果绑定Activity.RESULT_OK
finish();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
new AlertDialog.Builder(LoginActivity.this)
.setMessage(getString(R.string.errorId))
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
tourist_in_button.setEnabled(true);
}
});
}
private void findHistoryList() throws IOException {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/EasybuyCustomer.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
history.add(s);
//System.out.println(arrs[0] + " : " + arrs[1] + " : " + arrs[2]);
}
if (history.size() > 0) {
email.setText(history.get(0));
psd.setText(history.get(1));
}
br.close();
isr.close();
fis.close();
}
public void setHistoryList() throws IOException {
FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/EasybuyCustomer.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write("");
bw.write(email.getText().toString());
bw.newLine();
bw.write(psd.getText().toString());
bw.newLine();
bw.close();
osw.close();
fos.close();
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev)) {
hideSoftInput(v.getWindowToken());
}
}
return super.dispatchTouchEvent(ev);
}
private boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] l = { 0, 0 };
v.getLocationInWindow(l);
int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
+ v.getWidth();
if (event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom) {
return false;
} else {
return true;
}
}
return false;
}
private void hideSoftInput(IBinder token) {
if (token != null) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token,
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//按下键盘上返回按钮
if(keyCode == KeyEvent.KEYCODE_BACK){
new AlertDialog.Builder(this)
.setMessage(getString(R.string.youconfirmtologout))
.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
a=a+1;
finish();
}
}).show();
return true;
}else{
return super.onKeyDown(keyCode, event);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
this.unregisterReceiver(myNetReceiver);
if(a>0){
System.exit(0);
}
a=0;
}
}
Finally I got my answer,why creating a separate height layout was not working.
Though screen height of samsung s8 is 692 dp,but 25dp is not available as It is used by system UI.
Apparently it was stated in developer.android.com.
The Android system might use some of the screen for system UI (such as the system bar at the bottom of the screen or the status bar at the top), so some of the screen might not be available for your layout.
Therefore,subtracting 25 dp from 692 gives 667dp.Creating layout-h667dp worked.
I went to this post.
https://medium.com/#elye.project/an-important-note-when-managing-different-screen-height-3140e26e381a
I am new to android and now I am creating a app with splash screen as a launcher activity.
When I am trying to open the app it shows unable to add window token is not valid is your activity running.But if I open the app second time then it is working fine
My code is here:
public class SplashScreenActivity extends Activity {
private String mSavedEmail;
private String mSavedPassword;
public static SplashScreenActivity sInstance = null;
private User mUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_splash_screen);
SplashScreenActivity.sInstance = SplashScreenActivity.this;
/* Initiate Crittercism */
Crittercism.initialize(SplashScreenActivity.this, Const.CRITTERCISM_APP_ID);
new Thread(new Runnable() {
#Override
public void run() {
new CouchDB();
}
}).start();
// new UsersManagement();
String language = SampleApp.getPreferences().getGuiLanguage();
if (!language.equals("")) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
if (SampleApp.hasNetworkConnection()) {
if (checkIfUserSignIn()) {
boolean isLinked = false;
mSavedEmail = SampleApp.getPreferences().getUserEmail();
mSavedPassword = SampleApp.getPreferences().getUserPassword();
if (mSavedPassword.equals("")) {
isLinked = true;
mSavedPassword = SampleApp.getPreferences().getUserLinkedPassword();
}
mUser = new User();
CouchDB.authAsync(mSavedEmail, mSavedPassword, isLinked, new AuthListener(), SplashScreenActivity.this, false);
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreenActivity.this,
SignInActivity.class));
//finish();
}
}, 2000);
}
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this,
SignInActivity.class);
intent.putExtra(Const.SIGN_IN, true);
SplashScreenActivity.this.startActivity(intent);
Log.v("sample", "SplashScreenActivity starts SignInActivity");
Toast.makeText(SplashScreenActivity.this,
getString(R.string.no_internet_connection),
Toast.LENGTH_LONG).show();
}
}, 2000);
}
}
catch (Exception e){
}
}
#Override
protected void onResume() {
super.onResume();
overridePendingTransition(0, 0);
}
private boolean checkIfUserSignIn() {
boolean isSessionSaved = false;
Preferences prefs = LasteekApp.getPreferences();
if (prefs.getUserEmail() == null
|| (prefs.getUserPassword() == null && prefs.getUserLinkedPassword() == null)) {
isSessionSaved = false;
} else if (prefs.getUserEmail().equals("")
&& (prefs.getUserPassword() != null && prefs.getUserPassword().equals(""))) {
isSessionSaved = false;
}
else if (prefs.getUserEmail().equals("")
&& (prefs.getUserLinkedPassword() != null && prefs.getUserLinkedPassword().equals(""))) {
isSessionSaved = false;
}
else {
isSessionSaved = true;
}
return isSessionSaved;
}
private void signIn(User u) {
UsersManagement.setLoginUser(u);
UsersManagement.setToUser(u);
UsersManagement.setToGroup(null);
Log.d("User", "GetEmail "+u.getEmail());
boolean openPushNotification = getIntent().getBooleanExtra(
Const.PUSH_INTENT, false);
Intent intent = new Intent(SplashScreenActivity.this,
MyProfileActivity.class);
if (openPushNotification) {
intent = getIntent();
intent.setClass(SplashScreenActivity.this,
MyProfileActivity.class);
}
//parse URI hookup://user/[ime korisnika] and hookup://group/[ime grupe]
Uri userUri = getIntent().getData();
//If opened from link
if (userUri != null) {
String scheme = userUri.getScheme(); // "hookup"
String host = userUri.getHost(); // "user" or "group"
if (host.equals("user")) {
List<String> params = userUri.getPathSegments();
String userName = params.get(0); // "ime korisnika"
intent.putExtra(Const.USER_URI_INTENT, true);
intent.putExtra(Const.USER_URI_NAME, userName);
} else if (host.equals("group")) {
List<String> params = userUri.getPathSegments();
String groupName = params.get(0); // "ime grupe"
intent.putExtra(Const.GROUP_URI_INTENT, true);
intent.putExtra(Const.GROUP_URI_NAME, groupName);
}
}
intent.putExtra(Const.SIGN_IN, true);
try{
if(u.getName().toString().equals("")||u.getName().toString()==null){
Log.v("lasteek", "SplashScreenActivity starts EditProfileActivity 1");
intent.putExtra(Const.NEWLY_SIGNED_UP, true);
SplashScreenActivity.this.startActivity(intent);
} else if (u.getTitlePosition().toString().equals("")||u.getTitlePosition().toString()==null) {
Log.v("sample", "SplashScreenActivity starts EditProfileActivity 2");
intent.putExtra(Const.NEWLY_SIGNED_UP, true);
SplashScreenActivity.this.startActivity(intent);
} else if (u.getFunction()==null) {
Log.v("sample", "SplashScreenActivity starts EditProfileActivity 3");
intent.putExtra(Const.NEWLY_SIGNED_UP, true);
SplashScreenActivity.this.startActivity(intent);
} else if (u.getIndustry()==null) {
Log.v("sample", "SplashScreenActivity starts EditProfileActivity 4");
intent.putExtra(Const.NEWLY_SIGNED_UP, true);
SplashScreenActivity.this.startActivity(intent);
} else {
Log.v("sample", "SplashScreenActivity starts MyProfileActivity");
SplashScreenActivity.this.startActivity(intent);
}
} catch (Exception e){
Log.e("Exception",e.toString());
}
//finish();
}
private void checkPassProtect (User user) {
if (sample.getPreferences().getPasscodeProtect())
{
Intent passcode = new Intent(SplashScreenActivity.this,
PasscodeActivity.class);
passcode.putExtra("protect", true);
SplashScreenActivity.this.startActivityForResult(passcode, 0);
}
else
{
signIn(user);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
signIn(mUser);
}
else {
startActivity(new Intent(SplashScreenActivity.this,
SignInActivity.class));
//finish();
}
super.onActivityResult(requestCode, resultCode, data);
}
private boolean authentificationOk(User user) {
boolean authentificationOk = false;
if (user.getEmail() != null && !user.getEmail().equals("")) {
if (user.getEmail().equals(mSavedEmail)) {
authentificationOk = true;
}
}
return authentificationOk;
}
private class AuthListener implements ResultListener<String>
{
#Override
public void onResultsSucceded(String result) {
boolean tokenOk = result.equals(Const.LOGIN_SUCCESS);
mUser = UsersManagement.getLoginUser();
if (tokenOk && mUser!=null) {
if (authentificationOk(mUser)) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
checkPassProtect(mUser);
}
}, 2000);
}
} else {
SideBarActivity.appLogout(false, false, true, false);
}
}
#Override
public void onResultsFail() {
SideBarActivity.appLogout(false, false, false, true);
}
}
public void onStart() {
super.onStart();
try {
if (SharedData.runningActivities == 0) {
// app enters foreground
}
SharedData.runningActivities++;
Log.v("sample.activitymonitor", "SplashScreenActivity enters foreground");
Log.v("sample.activitymonitor", "runningActivities=" + SharedData.runningActivities);
}
catch (Exception e){
}
}
public void onStop() {
super.onStop();
SharedData.runningActivities--;
if (SharedData.runningActivities == 0) {
// app goes to background
}
Log.v("sample.activitymonitor", "SplashScreenActivity enters background");
Log.v("sample.activitymonitor", "runningActivities=" + SharedData.runningActivities);
}
}
I have some problem with printing image to AGPtEK 58mm Mini Bluetooth Pocket POS Thermal Receipt Printer. I am trying to convert webview content into image (this is working fine) and after that I want to print it with this printer but it prints only solid black background. Here is my code:
public class PrintDemo extends Activity {
private static final int REQUEST_ENABLE_BT = 2;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int PERMISSIONS_REQUEST_BLUETOOTH = 1;
private static final String TAG_REQUEST_PERMISSION = "Request permission";
private static final int PERMISSIONS_REQUEST_INTERNET = 0;
private static final int PERMISSIONS_REQUEST_BT_ADMIN = 2;
private static final int PERMISSIONS_REQUEST_LOCATION = 3;
private static final String WEB_SITE = "Remembered Web Site";
private static final String IS_CHECKED = "Check box";
#Bind(R.id.btn_search)
Button btnSearch;
#Bind(R.id.btn_print)
Button btnSendDraw;
#Bind(R.id.btn_open)
Button btnSend;
#Bind(R.id.btn_close)
Button btnClose;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING:
Log.d("State", "Connecting...");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Log.d("State", "Not found");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
String path;
File dir;
File file;
#Bind(R.id.check_box)
CheckBox checkBox;
#Bind(R.id.txt_content)
EditText edtContext;
#Bind(R.id.web_view)
WebView webView;
BluetoothService mService;
BluetoothDevice con_dev;
private SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.main);
ButterKnife.bind(this);
mService = new BluetoothService(this, mHandler);
if (!mService.isAvailable()) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDefaultTextEncodingName("utf-8");
webView.setWebViewClient(new WebViewClient() {
#SuppressLint("SdCardPath")
#Override
public void onPageFinished(final WebView view, String url) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
siteToImage(view);
}
}, 5000);
}
});
sharedPref = this.getPreferences(Context.MODE_PRIVATE);
checkPermissions();
}
private void siteToImage(WebView view) {
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap(
picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setRememberedWeb() {
if (checkBox.isChecked()) {
String rememberedWeb = sharedPref.getString(WEB_SITE, "");
if (!rememberedWeb.equals("")) {
edtContext.setText(rememberedWeb);
}
}
}
#Override
protected void onPause() {
super.onPause();
saveState(checkBox.isChecked());
}
#Override
protected void onResume() {
super.onResume();
checkBox.setChecked(load());
setRememberedWeb();
}
private void saveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(IS_CHECKED, isChecked);
if (isChecked) {
editor.putString(WEB_SITE, edtContext.getText().toString());
} else {
editor.putString(WEB_SITE, getString(R.string.txt_content));
}
editor.apply();
}
private boolean load() {
return sharedPref.getBoolean(IS_CHECKED, false);
}
private boolean checkPermissions() {
int permissionCheck =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH);
int permissionInternet =
ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET);
int permissionBTAdmin =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN);
int permissionLocation =
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bluetooth_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.BLUETOOTH)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTPermission();
}
return false;
} else if (permissionInternet == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_internet_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestInternetPermission();
}
return false;
} else if (permissionBTAdmin == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bt_admin_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTAdminPermission();
}
return false;
} else if (permissionLocation == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_location_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestLocationPermission();
}
return false;
} else {
return true;
}
}
private void requestLocationPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
private void requestBTAdminPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},
PERMISSIONS_REQUEST_BT_ADMIN);
}
private void requestInternetPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.INTERNET},
PERMISSIONS_REQUEST_INTERNET);
}
private void requestBTPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH},
PERMISSIONS_REQUEST_BLUETOOTH);
}
#Override
public void onStart() {
super.onStart();
if (!mService.isBTopen()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_print);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btn_open);
btnSend.setOnClickListener(new ClickEvent());
btnClose = (Button) this.findViewById(R.id.btn_close);
btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("TAG", ex.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else {
finish();
}
break;
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
}
}
#SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, file.getPath());
sendData = pg.printDraw();
mService.write(sendData);
}
public void downloadContent() {
if (!edtContext.getText().toString().equals("") && !edtContext.getText().toString().equals("https://")) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(edtContext.getText().toString())
.build();
HttpService service = retrofit.create(HttpService.class);
Call<ResponseBody> result = service.getContent();
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response) {
try {
if (response.body() != null) {
String summary = response.body().string();
webView.loadData(summary, "text/html; charset=utf-8", null);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
public interface HttpService {
#GET("/")
Call<ResponseBody> getContent();
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
downloadContent();
} else if (v == btnClose) {
mService.stop();
} else if (v == btnSendDraw) {
printImage();
}
}
}
}
The result is almost what I want you can see by yourself, but the printed image is not clear:
I fixed it guys, this was the problem, the method siteToImage(). Here are the changes I hope it will helps someone:
private void siteToImage() {
webView.measure(View.MeasureSpec.makeMeasureSpec(
View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
webView.setDrawingCacheEnabled(true);
webView.buildDrawingCache();
Bitmap b = Bitmap.createBitmap(webView.getMeasuredWidth(),
webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Paint paint = new Paint();
int iHeight = b.getHeight();
c.drawBitmap(b, 0, iHeight, paint);
webView.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
b.compress(Bitmap.CompressFormat.PNG, 50, fos);
fos.flush();
fos.close();
b.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
I have implemented Twilio in my android app for outgoing and incoming calls. But I'm facing an issue while getting incoming call with the background service. The issue is that I get calls in first 30-40 mins only. After sometime phone stops getting incoming calls. I tried so much. Please respond me soon. I'm sharing code with you too.
I get token from a background service which generates token after a time period.
IncomingCallService.java
public class IncomingCallService extends Service implements LoginListener,
BasicConnectionListener, BasicDeviceListener, View.OnClickListener,
CompoundButton.OnCheckedChangeListener,
RadioGroup.OnCheckedChangeListener {
private static Handler handler, handler_login;
public IncomingPhone phone;
SharedPreferences login_details;
Vibrator vibrator;
Ringtone r;
Uri notification;
public static final String LOGIN_DETAILS = "XXXXXXXX";
AudioManager am;
Intent intent;
public static String DEFAULT_CLIENT_NAME = "developer";
static String Twilio_id = "",
INCOMING_AUTH_PHP_SCRIPT = MenuItems.INCOMING_AUTH_PHP_SCRIPT
+ MenuItems.Twilio_id;
Runnable newrun;
Activity context;
Context ctx;
static String op_id = "";
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
login_details = getSharedPreferences(LOGIN_DETAILS,
Context.MODE_PRIVATE);
if (login_details.contains("twilio_Id")) {
Twilio_id = login_details.getString("twilio_Id", "");
}
handler_login = new Handler();
handler_login.postDelayed(new Runnable() {
#Override
public void run() {
Login();
handler_login.postDelayed(this, 20000);
}
}, 1000);
}
public void Login() {
phone = IncomingPhone.getInstance(getApplicationContext());
phone.setListeners(this, this, this);
phone.login(DEFAULT_CLIENT_NAME, true, true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.intent = intent;
// I know getIntent always return NULL in service
if (intent != null) {
op_id = intent.getStringExtra("operator_id");
onCallHandler();
}
return START_STICKY;
}
public void onCallHandler() {
handler = new Handler();
newrun = new Runnable() {
#Override
public void run() {
handler.removeCallbacks(newrun);
new IncomingTokenTask().execute();
if (phone.handleIncomingIntent(intent)) {
}
handler.postDelayed(this, 2000000);
}
};
handler.postDelayed(newrun, 8000000);
}
class IncomingTokenTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
IncomingPhone.capabilityToken = EntityUtils
.toString(entity);
}
}
The BasicPhone class of twilio
public class IncomingPhone implements DeviceListener, ConnectionListener {
private static final String TAG = "IncomingPhone";
static String decodedString = "";
static String capabilityToken = "";
// TODO: change this to point to the script on your public server
private static final String AUTH_PHP_SCRIPT = MenuItems.INCOMING_AUTH_PHP_SCRIPT+MenuItems.Twilio_id;
public interface LoginListener {
public void onLoginStarted();
public void onLoginFinished();
public void onLoginError(Exception error);
}
public interface BasicConnectionListener {
public void onIncomingConnectionDisconnected();
public void onConnectionConnecting();
public void onConnectionConnected();
public void onConnectionFailedConnecting(Exception error);
public void onConnectionDisconnecting();
public void onConnectionDisconnected();
public void onConnectionFailed(Exception error);
}
public interface BasicDeviceListener {
public void onDeviceStartedListening();
public void onDeviceStoppedListening(Exception error);
}
private static IncomingPhone instance;
public static final IncomingPhone getInstance(Context context) {
if (instance == null)
instance = new IncomingPhone(context);
return instance;
}
private final Context context;
private LoginListener loginListener;
private BasicConnectionListener basicConnectionListener;
private BasicDeviceListener basicDeviceListener;
private static boolean twilioSdkInited;
private static boolean twilioSdkInitInProgress;
private boolean queuedConnect;
private Device device;
private Connection pendingIncomingConnection;
private Connection connection;
private boolean speakerEnabled;
private String lastClientName;
private boolean lastAllowOutgoing;
private boolean lastAllowIncoming;
private IncomingPhone(Context context) {
this.context = context;
}
public void setListeners(LoginListener loginListener,
BasicConnectionListener basicConnectionListener,
BasicDeviceListener basicDeviceListener) {
this.loginListener = loginListener;
this.basicConnectionListener = basicConnectionListener;
this.basicDeviceListener = basicDeviceListener;
}
private void obtainCapabilityToken(String clientName,
boolean allowOutgoing, boolean allowIncoming) {
StringBuilder url = new StringBuilder();
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient httpclient = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory
.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(
httpclient.getParams(), registry);
#SuppressWarnings("unused")
DefaultHttpClient httpClient = new DefaultHttpClient(mgr,
httpclient.getParams());
// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
url.append(AUTH_PHP_SCRIPT);
// This runs asynchronously!
new GetAuthTokenAsyncTask().execute(url.toString());
}
private boolean isCapabilityTokenValid() {
if (device == null || device.getCapabilities() == null)
return false;
long expTime = (Long) device.getCapabilities().get(
Capability.EXPIRATION);
return expTime - System.currentTimeMillis() / 1000 > 0;
}
//
private void updateAudioRoute() {
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(speakerEnabled);
}
public void login(final String clientName, final boolean allowOutgoing,
final boolean allowIncoming) {
if (loginListener != null)
loginListener.onLoginStarted();
this.lastClientName = clientName;
this.lastAllowOutgoing = allowOutgoing;
this.lastAllowIncoming = allowIncoming;
if (!twilioSdkInited) {
if (twilioSdkInitInProgress)
return;
twilioSdkInitInProgress = true;
Twilio.setLogLevel(Log.DEBUG);
Twilio.initialize(context, new Twilio.InitListener() {
#Override
public void onInitialized() {
twilioSdkInited = true;
twilioSdkInitInProgress = false;
obtainCapabilityToken(clientName, allowOutgoing,
allowIncoming);
}
#Override
public void onError(Exception error) {
twilioSdkInitInProgress = false;
if (loginListener != null)
loginListener.onLoginError(error);
}
});
} else {
obtainCapabilityToken(clientName, allowOutgoing, allowIncoming);
}
}
private void reallyLogin(final String capabilityToken) {
try {
if (device == null) {
device = Twilio.createDevice(capabilityToken, this);
Intent intent = new Intent(context, IncomingPhoneActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(
context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
device.setIncomingIntent(pendingIntent);
} else
device.updateCapabilityToken(capabilityToken);
if (loginListener != null)
loginListener.onLoginFinished();
if (queuedConnect) {
// If someone called connect() before we finished initializing
// the SDK, let's take care of that here.
connect(null);
queuedConnect = false;
}
} catch (Exception e) {
if (device != null)
device.release();
device = null;
if (loginListener != null)
loginListener.onLoginError(e);
}
}
public void setSpeakerEnabled(boolean speakerEnabled) {
if (speakerEnabled != this.speakerEnabled) {
this.speakerEnabled = speakerEnabled;
updateAudioRoute();
}
}
public void connect(Map<String, String> inParams) {
if (twilioSdkInitInProgress) {
// If someone calls connect() before the SDK is initialized, we'll
// remember
// that fact and try to connect later.
queuedConnect = true;
return;
}
if (!isCapabilityTokenValid())
login(lastClientName, lastAllowOutgoing, lastAllowIncoming);
if (device == null)
return;
if (canMakeOutgoing()) {
disconnect();
connection = device.connect(inParams, this);
if (connection == null && basicConnectionListener != null)
basicConnectionListener
.onConnectionFailedConnecting(new Exception(
"Couldn't create new connection"));
}
}
public void disconnect() {
IncomingPhoneActivity.incomingAlert = null;
if (connection != null) {
connection.disconnect(); // will null out in onDisconnected()
if (basicConnectionListener != null)
basicConnectionListener.onConnectionDisconnecting();
}
}
public void acceptConnection() {
if (pendingIncomingConnection != null) {
if (connection != null)
disconnect();
pendingIncomingConnection.accept();
connection = pendingIncomingConnection;
pendingIncomingConnection = null;
}
}
public void connecta(String phoneNumber) {
Toast.makeText(context, "Calling...", Toast.LENGTH_SHORT).show();
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("group_id", "11");
// String capabilityToken;
try {
device = Twilio
.createDevice(decodedString, this /* DeviceListener */);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
device.disconnectAll();
} catch (Exception e) {
e.printStackTrace();
}
connection = device.connect(parameters, this);
if (connection == null) {
Log.w(TAG, "Failed to create new connection");
}
}
public void ignoreIncomingConnection() {
if (pendingIncomingConnection != null) {
pendingIncomingConnection.ignore();
}
}
public boolean isConnected() {
return connection != null
&& connection.getState() == Connection.State.CONNECTED;
}
public Connection.State getConnectionState() {
return connection != null ? connection.getState()
: Connection.State.DISCONNECTED;
}
public boolean hasPendingConnection() {
return pendingIncomingConnection != null;
}
public boolean handleIncomingIntent(Intent intent) {
Device inDevice = intent.getParcelableExtra(Device.EXTRA_DEVICE);
Connection inConnection = intent
.getParcelableExtra(Device.EXTRA_CONNECTION);
if (inDevice == null && inConnection == null)
return false;
intent.removeExtra(Device.EXTRA_DEVICE);
intent.removeExtra(Device.EXTRA_CONNECTION);
if (pendingIncomingConnection != null) {
Log.i(TAG, "A pending connection already exists");
inConnection.ignore();
return false;
}
pendingIncomingConnection = inConnection;
pendingIncomingConnection.setConnectionListener(this);
return true;
}
public boolean canMakeOutgoing() {
if (device == null)
return false;
Map<Capability, Object> caps = device.getCapabilities();
return caps.containsKey(Capability.OUTGOING)
&& (Boolean) caps.get(Capability.OUTGOING);
}
public boolean canAcceptIncoming() {
if (device == null)
return false;
Map<Capability, Object> caps = device.getCapabilities();
return caps.containsKey(Capability.INCOMING)
&& (Boolean) caps.get(Capability.INCOMING);
}
public void setCallMuted(boolean isMuted) {
if (connection != null) {
connection.setMuted(isMuted);
}
}
#Override
/* DeviceListener */
public void onStartListening(Device inDevice) {
if (basicDeviceListener != null)
basicDeviceListener.onDeviceStartedListening();
}
#Override
/* DeviceListener */
public void onStopListening(Device inDevice) {
if (basicDeviceListener != null)
basicDeviceListener.onDeviceStoppedListening(null);
}
#Override
/* DeviceListener */
public void onStopListening(Device inDevice, int inErrorCode,
String inErrorMessage) {
if (basicDeviceListener != null)
basicDeviceListener.onDeviceStoppedListening(new Exception(
inErrorMessage));
}
#Override
/* DeviceListener */
public boolean receivePresenceEvents(Device inDevice) {
return false;
}
#Override
/* DeviceListener */
public void onPresenceChanged(Device inDevice, PresenceEvent inPresenceEvent) {
}
#Override
/* ConnectionListener */
public void onConnecting(Connection inConnection) {
if (basicConnectionListener != null)
basicConnectionListener.onConnectionConnecting();
}
#Override
/* ConnectionListener */
public void onConnected(Connection inConnection) {
updateAudioRoute();
if (basicConnectionListener != null)
basicConnectionListener.onConnectionConnected();
}
#Override
/* ConnectionListener */
public void onDisconnected(Connection inConnection) {
if (inConnection == connection) {
connection = null;
if (basicConnectionListener != null)
basicConnectionListener.onConnectionDisconnected();
} else if (inConnection == pendingIncomingConnection) {
pendingIncomingConnection = null;
if (basicConnectionListener != null)
basicConnectionListener.onIncomingConnectionDisconnected();
}
}
#Override
/* ConnectionListener */
public void onDisconnected(Connection inConnection, int inErrorCode,
String inErrorMessage) {
if (inConnection == connection) {
connection = null;
if (basicConnectionListener != null)
basicConnectionListener
.onConnectionFailedConnecting(new Exception(
inErrorMessage));
}
}
private class GetAuthTokenAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
IncomingPhone.this.reallyLogin(result);
}
#Override
protected String doInBackground(String... params) {
try {
capabilityToken = HttpHelper.httpGet(params[0]);
decodedString = capabilityToken.replace("\"", "");
} catch (Exception e) {
e.printStackTrace();
}
return decodedString;
}
}
}
And the activity which opens after getting incoming call via Service class.
public class IncomingPhoneActivity extends Activity implements LoginListener,
BasicConnectionListener, BasicDeviceListener, View.OnClickListener,
CompoundButton.OnCheckedChangeListener,
RadioGroup.OnCheckedChangeListener {
private static final Handler handler = new Handler();
public IncomingPhone phone;
SharedPreferences login_details;
Vibrator vibrator;
private LinearLayout disconnect_btn;
private LinearLayout mainButton;
private ToggleButton speakerButton;
private ToggleButton muteButton;
private EditText logTextBox;
static AlertDialog incomingAlert;
private EditText outgoingTextBox;
private EditText clientNameTextBox;
private Button capabilitesButton;
private CheckBox incomingCheckBox, outgoingCheckBox;
Button call_btn, dis_call_btn, updateButton;
public static String AUTH_PHP_SCRIPT, rating1, rating2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.call_screen);
Intent intent = getIntent();
Operator_id = intent.getStringExtra("operator_id");
gps = new GPSTracker(IncomingPhoneActivity.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
} else {
// gps.showSettingsAlert();
latitude = 0.00;
longitude = 0.00;
}
login_details = getSharedPreferences(LOGIN_DETAILS,
Context.MODE_PRIVATE);
if (login_details.contains("twilio_Id")) {
Twilio_id = login_details.getString("twilio_Id", "");
}
AUTH_PHP_SCRIPT = "http://xxxxxxxxxxxxxx/getGenToken?group_id="
+ Operator_id + "&twilio_id=" + Twilio_id + "&latitude="
+ latitude + "&longitude=" + longitude;
disconnect_btn = (LinearLayout) findViewById(R.id.d_call);
mainButton = (LinearLayout) findViewById(R.id.call);
call_btn = (Button) findViewById(R.id.call_btn);
dis_call_btn = (Button) findViewById(R.id.d_call_btn);
mainButton.setOnClickListener(this);
call_btn.setOnClickListener(this);
dis_call_btn.setOnClickListener(this);
disconnect_btn.setOnClickListener(this);
mainButton.setEnabled(false);
call_btn.setEnabled(false);
speakerButton = (ToggleButton) findViewById(R.id.speaker_btn);
speakerButton.setOnCheckedChangeListener(this);
muteButton = (ToggleButton) findViewById(R.id.mute_btn);
muteButton.setOnCheckedChangeListener(this);
logTextBox = (EditText) findViewById(R.id.log_text_box);
outgoingTextBox = (EditText) findViewById(R.id.outgoing_client);
clientNameTextBox = (EditText) findViewById(R.id.client_name);
clientNameTextBox.setText(DEFAULT_CLIENT_NAME);
capabilitesButton = (Button) findViewById(R.id.capabilites_button);
capabilitesButton.setOnClickListener(this);
outgoingCheckBox = (CheckBox) findViewById(R.id.outgoing);
incomingCheckBox = (CheckBox) findViewById(R.id.incoming);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (MenuItems.Speaker == true) {
speakerButton.setVisibility(View.VISIBLE);
} else {
speakerButton.setVisibility(View.INVISIBLE);
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
phone = IncomingPhone.getInstance(getApplicationContext());
phone.setListeners(this, this, this);
phone.login(DEFAULT_CLIENT_NAME, outgoingCheckBox.isChecked(),
incomingCheckBox.isChecked());
}
private void syncMainButton() {
handler.post(new Runnable() {
public void run() {
if (IncomingPhone.decodedString.length() != 0) {
if (phone.isConnected()) {
switch (phone.getConnectionState()) {
default:
mainButton.setClickable(true);
mainButton.setEnabled(true);
call_btn.setEnabled(true);
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
break;
case DISCONNECTED:
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
break;
case CONNECTED:
mainButton.setVisibility(View.GONE);
disconnect_btn.setVisibility(View.VISIBLE);
disconnect_btn.setClickable(true);
break;
case CONNECTING:
mainButton.setVisibility(View.GONE);
disconnect_btn.setVisibility(View.VISIBLE);
disconnect_btn.setClickable(true);
break;
}
} else if (phone.hasPendingConnection()) {
mainButton.setClickable(true);
mainButton.setEnabled(true);
call_btn.setEnabled(true);
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
} else {
mainButton.setVisibility(View.VISIBLE);
disconnect_btn.setVisibility(View.GONE);
disconnect_btn.setClickable(false);
}
/*
* else { Toast.makeText(getApplicationContext(),
* "TRY AGAIN!", Toast.LENGTH_SHORT).show(); }
*/
}
}
});
}
public void onBackPressed() {
phone.disconnect();
incomingAlert = null;
Intent in = new Intent(IncomingPhoneActivity.this, MenuItems.class);
in.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(in);
finish();
}
class TokenTask extends AsyncTask<Void, Void, Void> {
String message;
JSONObject jsonResponse;
int crash_app;
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(AUTH_PHP_SCRIPT);
try {
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
IncomingPhone.capabilityToken = EntityUtils
.toString(entity);
IncomingPhone.decodedString = IncomingPhone.capabilityToken
.replace("\"", "");
}
}
} catch (Exception e) {
crash_app = 5;
message = "Something went wrong. Please try again later.";
return null;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (status.equals("success")) {
final Handler handler12 = new Handler();
handler12.postDelayed(new Runnable() {
public void run() {
mainButton.setEnabled(true);
call_btn.setEnabled(true);
mainButton
.setBackgroundResource(R.drawable.light_green_connect);
}
}, 3000);
}
if (status.equals("failure")) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
// mainButton.setBackgroundColor(Color.parseColor("#4ca64c"));
mainButton.setBackgroundResource(R.drawable.dark_green_connect);
mainButton.setEnabled(false);
call_btn.setEnabled(false);
}
}
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
#Override
public void onResume() {
super.onResume();
if (phone.handleIncomingIntent(getIntent())) {
showIncomingAlert();
addStatusMessage(R.string.got_incoming);
if (Utils.isNetworkAvailable(IncomingPhoneActivity.this)) {
syncMainButton();
} else {
Toast.makeText(IncomingPhoneActivity.this,
"No internet connection!!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (phone != null) {
phone.setListeners(null, null, null);
phone = null;
}
}
#Override
public void onClick(View view) {
if ((view.getId() == R.id.d_call) || (view.getId() == R.id.d_call_btn)) {
phone.disconnect();
incomingAlert = null;
phone.setSpeakerEnabled(false);
phone.setCallMuted(false);
Intent in = new Intent(IncomingPhoneActivity.this, MenuItems.class);
startActivity(in);
finish();
}
if ((view.getId() == R.id.call) || (view.getId() == R.id.call_btn)) {
} else if (view.getId() == R.id.capabilites_button) {
phone.login(clientNameTextBox.getText().toString(),
outgoingCheckBox.isChecked(), incomingCheckBox.isChecked());
}
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (group.getId() == R.id.input_select) {
if (checkedId == R.id.input_number) {
outgoingTextBox.setInputType(InputType.TYPE_CLASS_PHONE);
outgoingTextBox.setHint(R.string.outgoing_number);
} else {
outgoingTextBox.setInputType(InputType.TYPE_CLASS_TEXT);
outgoingTextBox.setHint(R.string.outgoing_client);
}
outgoingTextBox.setText("");
}
}
#Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
if (button.getId() == R.id.speaker_btn) {
phone.setSpeakerEnabled(isChecked);
} else if (button.getId() == R.id.mute_btn) {
phone.setCallMuted(isChecked);
}
}
private void addStatusMessage(final String message) {
handler.post(new Runnable() {
#Override
public void run() {
logTextBox.append('-' + message + '\n');
}
});
}
private void addStatusMessage(int stringId) {
addStatusMessage(getString(stringId));
}
private void showIncomingAlert() {
handler.post(new Runnable() {
#Override
public void run() {
if (incomingAlert == null) {
notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
r = RingtoneManager.getRingtone(getApplicationContext(),
notification);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
r.play();
break;
case AudioManager.RINGER_MODE_VIBRATE:
long pattern[] = { 0, 500, 200, 300, 500 };
vibrator.vibrate(pattern, 0);
break;
case AudioManager.RINGER_MODE_NORMAL:
r.play();
break;
}
incomingAlert = new AlertDialog.Builder(
IncomingPhoneActivity.this)
.setTitle(R.string.incoming_call)
.setCancelable(false)
.setMessage(R.string.incoming_call_message)
.setPositiveButton(R.string.answer,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
r.stop();
break;
case AudioManager.RINGER_MODE_VIBRATE:
vibrator.cancel();
break;
case AudioManager.RINGER_MODE_NORMAL:
r.stop();
break;
}
phone.acceptConnection();
disconnect_btn
.setVisibility(View.VISIBLE);
mainButton.setVisibility(View.GONE);
incomingAlert = null;
}
})
.setNegativeButton(R.string.ignore,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
r.stop();
break;
case AudioManager.RINGER_MODE_VIBRATE:
vibrator.cancel();
break;
case AudioManager.RINGER_MODE_NORMAL:
r.stop();
break;
}
phone.ignoreIncomingConnection();
incomingAlert = null;
}
})
.setOnCancelListener(
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(
DialogInterface dialog) {
phone.ignoreIncomingConnection();
}
}).create();
incomingAlert.show();
}
}
});
}
private void hideIncomingAlert() {
handler.post(new Runnable() {
#Override
public void run() {
if (incomingAlert != null) {
incomingAlert.dismiss();
incomingAlert = null;
}
}
});
}
#Override
public void onLoginStarted() {
addStatusMessage(R.string.logging_in);
}
#Override
public void onLoginFinished() {
addStatusMessage(phone.canMakeOutgoing() ? R.string.outgoing_ok
: R.string.no_outgoing_capability);
addStatusMessage(phone.canAcceptIncoming() ? R.string.incoming_ok
: R.string.no_incoming_capability);
syncMainButton();
}
#Override
public void onLoginError(Exception error) {
if (error != null)
addStatusMessage(String.format(getString(R.string.login_error_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.login_error_unknown);
syncMainButton();
}
#Override
public void onIncomingConnectionDisconnected() {
hideIncomingAlert();
addStatusMessage(R.string.incoming_disconnected);
syncMainButton();
}
#Override
public void onConnectionConnecting() {
addStatusMessage(R.string.attempting_to_connect);
syncMainButton();
}
#Override
public void onConnectionConnected() {
addStatusMessage(R.string.connected);
syncMainButton();
}
#Override
public void onConnectionFailedConnecting(Exception error) {
if (error != null)
addStatusMessage(String.format(
getString(R.string.couldnt_establish_outgoing_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.couldnt_establish_outgoing);
}
#Override
public void onConnectionDisconnecting() {
addStatusMessage(R.string.disconnect_attempt);
syncMainButton();
}
#Override
public void onConnectionDisconnected() {
addStatusMessage(R.string.disconnected);
syncMainButton();
}
#Override
public void onConnectionFailed(Exception error) {
if (error != null)
addStatusMessage(String.format(
getString(R.string.connection_error_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.connection_error);
syncMainButton();
}
#Override
public void onDeviceStartedListening() {
addStatusMessage(R.string.device_listening);
}
#Override
public void onDeviceStoppedListening(Exception error) {
if (error != null)
addStatusMessage(String.format(
getString(R.string.device_listening_error_fmt),
error.getLocalizedMessage()));
else
addStatusMessage(R.string.device_not_listening);
}
}