java - need help for keycode_home [duplicate] - java

This question already has answers here:
Keycode_home doesn't get called ANDROID
(4 answers)
Closed 8 years ago.
i need help in my app which shows a toast when home button is pressed, back button is pressed and it check if the phone have got the nav bar
MainActivity.java
package com.example.myapp;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
Toast.makeText(getApplicationContext(), "goodbye! (home button pressed)", Toast.LENGTH_LONG).show(); //doesn't work here
finish();
return true;
}
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Toast.makeText(getApplicationContext(), "goodbye! (back button pressed)", Toast.LENGTH_LONG).show();
finish();
return true;
}
return false;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
boolean hasHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME);
if (hasBackKey && hasHomeKey) {
// no navigation bar
Toast.makeText(getApplicationContext(), "no nav bar", Toast.LENGTH_LONG).show();
} else {
// navigation bar
Toast.makeText(getApplicationContext(), "nav bar", Toast.LENGTH_LONG).show();
}
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
I have got a nexus 5 so it has the nav bar, and I think this is the problem
how can I fix the prolem?
nexus 5, android 4.4.3
thanks

The framework never sends KEYCODE_HOME to apps.
Right now your best indicator of when the user leaves your app (as opposed to a single activity), is listening for TRIM_MEMORY_UI_HIDDEN in onTrimMemory(int).
public class MainActivity extends Activity {
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (level == TRIM_MEMORY_UI_HIDDEN) {
Context ctx = getApplicationContext();
Toast.makeText(ctx, "gone", Toast.LENGTH_SHORT).show();
}
}
}
Also you should not finish() just because the user leaves, then when the user gets back the activity will always have to be recreated from scratch, without state.

Related

WebView videos on fullscreen

Please see below my code: I have tried several codes that fulllscreen for videos and I did not succeed, or I did not know how to install.
I need enable fullscreen for videos for any player video
package com.androidapp.www.WEBSITE;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
WebView wv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView)findViewById(R.id.webView);
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
wv.loadUrl("https://www.mfshd.net");
wv.setWebViewClient(new MobWebViewClient());
}
#Override
public void onBackPressed() {
if(wv.canGoBack()){
wv.goBack();
}else{
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MobWebViewClient extends WebViewClient {
}
}
Firstly you have to add a FrameLayout in your activity_main and make its visibility "gone"
Secondly add this code to your MainActivity:
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
wv.setWebChromeClient(new WebChromeClient() {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomView = view;
wv.setVisibility(View.GONE);
frameLayout.setVisibility(View.VISIBLE);
frameLayout.addView(view);
mCustomViewCallback = callback;
}
#Override
public void onHideCustomView() {
super.onHideCustomView();
if (mCustomView == null)
return;
wv.setVisibility(View.VISIBLE);
frameLayout.setVisibility(View.GONE);
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
frameLayout.removeView(mCustomView);
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
});

Android WebView app resetting on rotation

I am having some issues with webview where on rotation the app resets to the default URL. I have hunted round for a solution and tried a number on here and run into different issues with each.
This is what is in my .java code
package uk.co.grcade.grcade;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebViewClient;
public class GRcade extends Activity {
WebView web;
String webURL = "http://grcade.co.uk";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grcade);
if (savedInstanceState != null)
{
web.loadUrl(webURL);
}
web = (WebView) findViewById(R.id.web);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(webURL);
web.setPadding(0, 0, 0, 0);
web.getSettings().setLoadWithOverviewMode(true);
web.getSettings().setUseWideViewPort(true);
web.getSettings().setSupportZoom(true);
web.getSettings().setBuiltInZoomControls(true);
web.getSettings().setDisplayZoomControls(false);
}
#Override
protected void onSaveInstanceState (Bundle outState )
{
super.onSaveInstanceState(outState);
web.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
web.restoreState(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_grcade, menu);
return true;
}
private class HelloWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView web, String url) {
web.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int ketCode, KeyEvent event) {
if ((ketCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I got the code from a post on here but can't comment to ask why the line:
web = (WebView) findViewById(R.id.web);
is showing an unable to resolve symbol error, I am new to this whole thing so would appreciate some help on how I can get that error to go away and allow me to have a webview app that can be rotated without resetting back to the default page.
Thanks.
Your problem is in OnCreate method.
Your code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grcade);
if (savedInstanceState != null)
{
web.loadUrl(webURL);
}
.........
.........
You check if your Bundle object is not null and you load the URL. Instead, you should be restoring the state when the bundle object is not null. Something like this
if (savedInstanceState != null) {
webView.restoreState(savedInstanceState);
} else {
webView.loadUrl("http://grcade.co.uk");
}

Android Studio, Call to different class in different file

I have written the piece of code below to reference to the class called Forecast Fragment, and the app runs. but on line 33, i am getting a error for "cannot resolve symbol 'android' "
package com.example.sunshinepre_beta;
import android.os.Bundle;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
int commit = getSupportFragmentManager().beginTransaction()
.add(R.id.container, new com.example.android.sunshinepre_beta.app.ForecastFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Replace new com.example.android.sunshinepre_beta.app.ForecastFragment() with new ForecastFragment()
Also move ForecastFragment.java to the same folder where MainActivity is.

Android app crashes, due to count down timer?

I have made an app recently and I added a count down timer one day and made a few changes here and there and now when I run the app on my (actual) Galaxy Note 3 it crashes as soon as I hit the Play button below are my LevelOne.java file and my MainActivity.Java file. By the way the logcat shows nothing as if it doesn't realize it crashed.
LevelOne.java
package com.parker.orangedot;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class LevelOne extends ActionBarActivity {
Button myButton;
LevelOne context;
CountDownTimer timer = new CountDownTimer(1500, 1500)
{
#Override
public void onFinish() {
Intent intent = new Intent(context, Scores.class);
startActivity(intent);
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_level_one);
//ass soon as this activity is created, I start my timer.
timer.start();
myButton = (Button) findViewById(R.id.button2);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
timer.cancel();
}});
}
#Override
public void onBackPressed() {
}
public void next(View view) {
// Do something in response to button
Intent intent = new Intent(this, LevelTwo.class);
startActivity(intent);
}
public void openScores(View view) {
// Do something in response to button
Intent intent = new Intent(this, Scores.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.level_one, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_level_one,
container, false);
return rootView;
}
}
}
MainActivity.java
package com.parker.orangedot;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void openScores(View view) {
// Do something in response to button
Intent intent = new Intent(this, Scores.class);
startActivity(intent);
}
public void play(View view) {
// Do something in response to button
Intent intent = new Intent(this, LevelOne.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
UPDATE:
When using the emulater for the Galaxy Nexus, pressing "play" does absolutely nothing.

Getting checkout button to navigate to checkout page

I am working in Eclipse and struggling with a certain step in my assignment so any help would be appriciated because I actually dont know how to do it even though I realise how glaringly simple it probably is...
I have a shopping app and I have created my CheckoutActivity... now... it needs to start when the user clicks the checkout button in my CartActivity.
I need to add code in the ocCreate method of my CartActivity (which I will provide below) that specifies the listener for the Checkout button. then I need to define a button variable named btn inside the onCreate. I then need to assign the button element from the view using the id that you specified in my activity_cart.xml layout.
All I have so far is this... and I have no idea what to do...
btn.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
//I cant figure out how to get it to start the CheckoutActivity
}
});
Just in case you need to see the code I have so far... here is the code I have for my cartActivty
package uk.ac.uk.st265.shopper;
import java.text.DecimalFormat;
import java.util.List;
import java.util.ResourceBundle.Control;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class CartActivity extends Activity {
CartListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
TextView text = (TextView) findViewById(R.id.total_price); // its not in
// XML
DecimalFormat df = new DecimalFormat("#.00");
text.setText("£"
+ df.format(((ShopperApp) getApplication()).getCartTotal()));
adapter = new CartListAdapter(this);
ListView cartList = (ListView) findViewById(R.id.cart_list);
adapter.setItemList(((ShopperApp) getApplication()).cart);
cartList.setAdapter(adapter);
// Show the Up button in the action bar.
setupActionBar();
//work5ass2part6
//btn.setOnClickListener(new OnClickListener() {
//public void onClick(final View v) {
// I cant figure out how to get it to start the CheckoutActivity
//}
//});
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cart, menu);
return true;
}
public class CartListAdapter extends BaseAdapter {
private final Context context;
private List<Product> itemList;
public CartListAdapter(Context c) {
context = c;
}
public void setItemList(List<Product> itemList) {
// this.itemList = itemList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View cell = convertView;
if (cell == null) {
// get layout from mobile xml
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
cell = inflater.inflate(R.layout.adapter_cart, parent, false);
}
Product p = itemList.get(position);
// set value into text view according to position
TextView textView = (TextView) cell
.findViewById(R.id.product_title);
textView.setText(p.getProductName());
textView = (TextView) cell.findViewById(R.id.product_info);
textView.setText("Price " + p.getPrice());
// set value into image view according to position
ImageView imgView = (ImageView) cell
.findViewById(R.id.product_image);
// clear the image
imgView.setImageDrawable(null);
// and load from the network
p.loadImage(imgView, 54, 54);
return cell;
}
public List<Product> getItemList() {
return itemList;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
case R.id.show_cart:
// Create the intent for the cart activity
Intent intent = new Intent(getApplicationContext(),
CartActivity.class);
startActivity(intent);
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
and here is the code I have so far on my CheckoutActivity:
package uk.ac.uk.st265.shopper;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class CheckoutActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkout);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.checkout, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
// myIntent.putExtra("key", value); //if you want to pass parameter
CurrentActivity.this.startActivity(myIntent);

Categories