Frame.GoBack minimizes the Application - windows-runtime

public Constructor1()
{
this.NavigationCacheMode = NavigationCacheMode.Enabled;
}
....
public Constructor2()
{
this.NavigationCacheMode = NavigationCacheMode.Enabled;
HardwareButtons.BackPressed += this.MainPage_BackPressed;
}
private void MainPage_BackPressed(object sender, BackPressedEventArgs e)
{
if(this.Frame.CanGoBack)
{
this.Frame.GoBack();
}
}
After I use the BackButton on my Windows Phone my Application minimizes itself. I have to go to the Task Manager and click on it to bring it back up.
Any suggestions why Frame.GoBack minimizes the Application?

private void MainPage_BackPressed(object sender, BackPressedEventArgs e)
{
if(this.Frame.CanGoBack)
{
e.Handled = true;
this.Frame.GoBack();
}
}
e.Handled = true; was the problem.

Related

Map fragment doesn't move to current location when Recreated

Greetings to the community. This is my first question, please guide me if I did any mistake.
I have four fragments in my app. An activity(Main Activity) that hosts all the four fragments.
Google Maps Fragment
Fragment two
Fragment three
Fragment four
When the application starts. Maps fragment is loaded and it shows marker at my current location. But when I move from Maps fragment to Fragment two and then came back to Map Fragment it doesn't show my current location
Here is the code
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Fragments
private MapsFragment mapsFragment = new MapsFragment();
private QrScanFragment qrScanFragment = new QrScanFragment();
private SeatsFullFragment seatsFullFragment = new SeatsFullFragment();
private EmergencyFragment emergencyFragment = new EmergencyFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initLayouts();
initListeners();
// Maps Fragment Loaded
mIvMaps.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
loadFragment(mapsFragment);
}
}
loadFragment(Fragment fragment)
public void loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frame_container, fragment)
.commit();
}
}
Moving b/w fragments
if (view == mLlMaps) {
if (!mapsFragment.isVisible()) {
loadFragment(mapsFragment);
mTvTitle.setText("Map");
}
mIvMaps.setImageResource(R.drawable.ic_map_pin_2_line_fill);
mIvMaps.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
} else if (view == mLlQrScan) {
if (!qrScanFragment.isVisible()) {
loadFragment(qrScanFragment);
mTvTitle.setText("ScanQR");
}
mIvQrScan.setImageResource(R.drawable.ic_baseline_qr_code_scanner_24_fill);
mIvQrScan.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
}
}
MapsFragment.java
public class MapsFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
private SupportMapFragment mapFragment;
// To get Current Location of Driver
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
public MapsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_maps, container, false);
buildLocationRequest(); // Request for current Location
buildLocationCallback(); // When location is provided
updateLocation(); // Fused Location Provider
// Child Fragment Manager copied from Uber
mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
// Request for current Location
private void buildLocationRequest() {
if (locationRequest == null) {
locationRequest = new LocationRequest();
locationRequest.setSmallestDisplacement(50f); // 50m
locationRequest.setInterval(15000); // 15s
locationRequest.setFastestInterval(10000); // 10s
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
// When location result is provided
private void buildLocationCallback() {
if (locationCallback == null) {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
LatLng newPosition = new LatLng(locationResult.getLastLocation().getLatitude(),
locationResult.getLastLocation().getLongitude());
// 18f is the radius of circle
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newPosition, 18f));
}
};
}
}
// Fused Location Provider
private void updateLocation() {
if (fusedLocationProviderClient == null) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "Permission Required", Toast.LENGTH_SHORT).show();
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.d("EB", "onMapReady: called");
// Check Permission
Dexter.withContext(getContext())
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
Toast.makeText(getContext(), "Permission Granted", Toast.LENGTH_SHORT).show();
}
fusedLocationProviderClient.getLastLocation().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
LatLng userLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
// 18f is the radius of circle
mMap.animateCamera(CameraUpdateFactory
.newLatLngZoom(userLatLng, 18f));
}
});
return true;
}
});
// Set Layout - Location Button
View locationButton = ((View) mapFragment.getView().findViewById(Integer.parseInt("1"))
.getParent())
.findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
//Right Bottom
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.setMargins(0, 0, 0, 50);
// Move to current Location
buildLocationRequest();
buildLocationCallback();
updateLocation();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
Toast.makeText(getContext(),
"Permission" + permissionDeniedResponse.getPermissionName() + "wasdenied",
Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
}
}).check();
// Change/Parse the Maps Style
try {
boolean success = googleMap.setMapStyle(MapStyleOptions
.loadRawResourceStyle(getContext(), R.raw.uber_maps_style));
if (!success)
Log.e("Error", "Style parsing Error");
} catch (Resources.NotFoundException e) {
Log.e("Error", e.getMessage());
}
}
}

How to add progress bar or progress ring for webview project for windows mobile app

I have created a Webview Project for windows phone app to load google.com. It's working fine but I'm unable to add a Progress bar or Progress Ring. Can any one please help me?
namespace App2
{
public sealed partial class MainPage : Page
{
private static readonly Uri HomeUri = new Uri("http://www.google.com", UriKind.Absolute);
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
WebViewControl.Navigate(HomeUri);
HardwareButtons.BackPressed += this.MainPage_BackPressed;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
HardwareButtons.BackPressed -= this.MainPage_BackPressed;
}
private void MainPage_BackPressed(object sender, BackPressedEventArgs e)
{
if (WebViewControl.CanGoBack)
{
WebViewControl.GoBack();
e.Handled = true;
}
}
private void Browser_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
if (!args.IsSuccess)
{
Debug.WriteLine("Navigation to this page failed, check your internet connection.");
}
}
}
}
In your XAML add a progress ring over the webview so that it overlaps webview for example
<Grid>
<Grid x:Name="webViewHolder" >
<WebView x:Name="wvPage" Loaded="WebView_Loaded" NavigationCompleted="WebView_NavigationCompleted" NavigationStarting="wvPage_NavigationStarting"></WebView>
</Grid>
<ProgressRing x:Name="myProgressRing" IsActive="True" Height="90" Width="90" Background="Transparent" Foreground="#EF4D17"/>
</Grid>
Now in code Behind
private void wvPage_NavigationStarting(Windows.UI.Xaml.Controls.WebView sender, WebViewNavigationStartingEventArgs args)
{
myProgressRing.IsActive = true;
}
.
.
.
private void WebView_NavigationCompleted(Windows.UI.Xaml.Controls.WebView sender, WebViewNavigationCompletedEventArgs args)
{
myProgressRing.IsActive = false;
}

Topshelf TimeoutException

I'm trying to use Topshelf Framework to create a windows service. But when i try to start the service, there is this exception :
" The service failed to start... System.Service.Process.TimeoutException : the waiting period has expired and the operation has not been completed"
This is my code :
public class MyService : ServiceControl
{
private System.Timers.Timer _timer;
public void MyService()
{
_timer = new System.Timers.Timer(10);
_timer.AutoReset = false;
_timer.Elapsed += new ElapsedEventHandler(TimerOnElapsed);
}
private void TimerOnElapsed(object source, ElapsedEventArgs e)
{
//all the operation to do at the startup
}
public bool Start(HostControl hostControl)
{
_timer.Start();
return true;
}
public bool Stop(HostControl hostControl)
{
_timer.Stop();
return true;
}
}
Thanks for any help :)
There are several issues I notice:
The current code would make the timer fire only once (you have AutoReset = false)
with TopShelf, the MyService class should look like this:
using System.Timers;
using Topshelf;
namespace TopShelfTestService
{
public class MyService
{
private System.Timers.Timer _timer;
public MyService()
{
_timer = new System.Timers.Timer(10);
_timer.AutoReset = true;
_timer.Elapsed += new ElapsedEventHandler(TimerOnElapsed);
}
private void TimerOnElapsed(object source, ElapsedEventArgs e)
{
//all the operation to do at the startup
}
public bool Start(HostControl hostControl)
{
_timer.Start();
return true;
}
public bool Stop(HostControl hostControl)
{
_timer.Stop();
return true;
}
}
}
and the console app/ Program.cs will look like so:
using Topshelf;
namespace TopShelfTestService
{
class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<MyService>(s =>
{
s.ConstructUsing(name => new MyService());
s.WhenStarted((tc, hostControl) => tc.Start(hostControl));
s.WhenStopped((tc, hostControl) => tc.Stop(hostControl));
});
x.RunAsLocalSystem();
x.SetDescription("Sample Topshelf Host"); //7
x.SetDisplayName("Test Service with TopShelf"); //8
x.SetServiceName("TopShelfTestService");
});
}
}
}

How to get the object reference of backstack pages

I am trying to save a list of backstack pages that are Tombstoned, so that when I navigate back to them, I can compare if they are present in this list. If yes, I'll restore its state.
Currently my code looks like this.
public partial class App : Application
{
public static List<PhoneApplicationPage> TombstonedPages = new List<PhoneApplicationPage>();
private void Application_Activated(object sender, ActivatedEventArgs e)
{
if(!e.IsApplicationInstancePreserved)
{
foreach (JournalEntry j in (Application.Current.RootVisual as PhoneApplicationFrame).BackStack)
{
TombstonedPages.Add(//What should i add here);
}
}
}
}
code in some PhoneApplicationPage
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//checking tombstone
if(e.NavigationMode== NavigationMode.Back && App.TombstonedPages.Contains(this) )
{
//restore state and delete entry from App.TombstonedPages
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
if(e.NavigationMode != NavigationMode.Back)
{
//save state
}
}
But I am unable to get a reference of pages from backstack. How should I do this? Is there a different way to do this?

Issue with Sound Recording in windowsphone8

My code works properly till page active. But after going back to another page when i again navigate on recording page it doesn't work.
here is sample code with page added.
public partial class MainPage : PhoneApplicationPage
{
private Microphone microphone = Microphone.Default;
private byte[] buffer;
private MemoryStream stream = new MemoryStream();
private SoundEffectInstance soundInstance;
private bool soundIsPlaying = false;
// Status images
private BitmapImage blankImage;
private BitmapImage microphoneImage;
private BitmapImage speakerImage;
public MainPage()
{
InitializeComponent();
// Timer to simulate the XNA Framework game loop (Microphone is
// from the XNA Framework). We also use this timer to monitor the
// state of audio playback so we can update the UI appropriately.
DispatcherTimer dt = new DispatcherTimer();
dt.Interval = TimeSpan.FromMilliseconds(33);
dt.Tick += new EventHandler(dt_Tick);
dt.Start();
microphone.BufferReady += new EventHandler<EventArgs>(microphone_BufferReady);
blankImage = new BitmapImage(new Uri("Images/blank.png", UriKind.RelativeOrAbsolute));
microphoneImage = new BitmapImage(new Uri("Images/microphone.png", UriKind.RelativeOrAbsolute));
speakerImage = new BitmapImage(new Uri("Images/speaker.png", UriKind.RelativeOrAbsolute));
}
void dt_Tick(object sender, EventArgs e)
{
try { FrameworkDispatcher.Update(); }
catch { }
if (true == soundIsPlaying)
{
if (soundInstance.State != SoundState.Playing)
{
// Audio has finished playing
soundIsPlaying = false;
// Update the UI to reflect that the
// sound has stopped playing
SetButtonStates(true, true, false);
UserHelp.Text = "press play\nor record";
StatusImage.Source = blankImage;
}
}
}
private void recordButton_Click(object sender, EventArgs e)
{
microphone.BufferDuration = TimeSpan.FromMilliseconds(500);
buffer = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)];
stream.SetLength(0);
microphone.Start();
SetButtonStates(false, false, true);
UserHelp.Text = "record";
StatusImage.Source = microphoneImage;
}
private void stopButton_Click(object sender, EventArgs e)
{
if (microphone.State == MicrophoneState.Started)
{
// In RECORD mode, user clicked the
// stop button to end recording
microphone.Stop();
}
else if (soundInstance.State == SoundState.Playing)
{
// In PLAY mode, user clicked the
// stop button to end playing back
soundInstance.Stop();
}
SetButtonStates(true, true, false);
UserHelp.Text = "ready";
StatusImage.Source = blankImage;
}
private void playButton_Click(object sender, EventArgs e)
{
if (stream.Length > 0)
{
// Update the UI to reflect that
// sound is playing
SetButtonStates(false, false, true);
UserHelp.Text = "play";
StatusImage.Source = speakerImage;
// Play the audio in a new thread so the UI can update.
Thread soundThread = new Thread(new ThreadStart(playSound));
soundThread.Start();
}
}
private void playSound()
{
// Play audio using SoundEffectInstance so we can monitor it's State
// and update the UI in the dt_Tick handler when it is done playing.
SoundEffect sound = new SoundEffect(stream.ToArray(), microphone.SampleRate, AudioChannels.Mono);
soundInstance = sound.CreateInstance();
soundIsPlaying = true;
soundInstance.Play();
}
private void SetButtonStates(bool recordEnabled, bool playEnabled, bool stopEnabled)
{
(ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = recordEnabled;
(ApplicationBar.Buttons[1] as ApplicationBarIconButton).IsEnabled = playEnabled;
(ApplicationBar.Buttons[2] as ApplicationBarIconButton).IsEnabled = stopEnabled;
}
}
Another page
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
}
}
Please if possible give some solution to it because my application is dependent on audio
recording..
Thank You very much....
microphone.BufferReady -= new EventHandler<EventArgs>(microphone_BufferReady);
write this code into OnNavigateFrom even.