How don't kill process after onStop? - java

Simple code:
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
private TabHost mTabHost;
private int a;
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
protected void onStop() {
super.onStop();
// The activity is about to become visible.
}
protected void onRestart() {
super.onRestart();
}
protected void onDestroy(){
super.onDestroy();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Activity activity = this;
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Zastępstwa").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Plan Lekcji").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("O programie").setContent(R.id.tab3));
webview = (WebView) findViewById(R.id.webView1);
webviewtwo = (WebView) findViewById(R.id.webView2);
final WebSettings webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
webview.restoreState(savedInstanceState.getBundle("stateone"));
webviewtwo.restoreState(savedInstanceState.getBundle("statetwo"));
webviewtwoSettings.setTextSize(TextSize.LARGER);
mTabHost.setCurrentTab(savedInstanceState.getInt("CURRENT_TAB"));
}
else{
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
webviewtwoSettings.setTextSize(TextSize.LARGER);
mTabHost.setCurrentTab(0);
}
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webview.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
webviewtwo.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webviewtwo.loadData(summary, "text/html","utf-8");
webviewtwoSettings.setTextSize(TextSize.NORMAL);
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
protected void onSaveInstanceState(Bundle outState) {
Bundle outStateone = new Bundle();
Bundle outStatetwo = new Bundle();
webview.saveState(outStateone);
webviewtwo.saveState(outStatetwo);
outState.putBundle("stateone", outStateone);
outState.putBundle("statetwo", outStatetwo);
outState.putInt("CURRENT_TAB", mTabHost.getCurrentTab());
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
final AlertDialog alertdialog= new AlertDialog.Builder(this).create();
alertdialog.setTitle("O Programie");
alertdialog.setMessage("Zmiany w 1.0.1: \n-Obsługa planu z dnia 17.10.2011\n-Drobne Poprawki");
alertdialog.setButton("Fajno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertdialog.cancel();
}
});
alertdialog.show();
return true;
case R.id.item2:
finish();
case R.id.item3:
if(mTabHost.getCurrentTab() == 0){
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
}
else if(mTabHost.getCurrentTab() == 1)
{
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
}
default:
return super.onOptionsItemSelected(item);
}
}
}
Now My problem. After i press back button onStop() code is executed and onDestroy. How i can don't kill app ? I wanna this app in background. Now when i press back button and open app, all data is again downloaded and loaded to webview. Soo how make this process work in background ?
Sorry for my haotic english :)
Sierran

Use Android service for doing something in Background rather then Activity.
And use Broadcast receiver to invoke your Activity from service. When something your background work finished.
Android - Service
And if you want to do some little then just override onKeyDown()
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// put your stuff here or just block the back button for perticular activity
return true;
}
return super.onKeyDown(keyCode, event);
}

I would recommend using a Service if you want to do something in the background and need it to be running more or less all the time. Check out the Service documentation here:
http://developer.android.com/reference/android/app/Service.html
An alternative in your case would be to create local caches of the websites.

Related

Webview back button problem (stack multiple clicks)

i have back button in my webview and its linked with loading screen (when i click back button its show loading animation (its named progressBar in the code).
But i have problem when i make fast few clicks my loading screen is looping.
Its any way to make the back button work only one time on page?
Like 1 click = 1 action, no more and stack.
For example i click on the back button, and its off for next click, but when page reloaded button work again.
Button przycisk_powrot = (Button) findViewById(R.id.przycisk_powrot);
przycisk_powrot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mywebView.goBack();
progressBar.setVisibility(View.VISIBLE);
}
});
Button przycisk_powrot = (Button) findViewById(R.id.przycisk_powrot);
przycisk_powrot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mywebView.goBack();
progressBar.setVisibility(View.VISIBLE);
}
});
#Override
public void onBackPressed(){
if(mywebView.canGoBack()) {
mywebView.goBack();
}
else{
super.onBackPressed();
}
}
public class WebViewClient extends android.webkit.WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
}
}, 1000);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean overrideUrlLoading = false;
progressBar.setVisibility(View.VISIBLE);
view.loadUrl(url);
return true;
}

onBackPressed() crashes my webview app

I am new to android development, I have tried to override onBackPress() to implement webView.GoBack(). But on pressing back key my apps getting crashed. Here is my MainActivity.java code. Am I doing something wrong ??
public class MainActivity extends AppCompatActivity {
private WebView webview;
/** Called when the activity is first created. */
public void onBackPressed (){
if (webview.isFocused() && webview.canGoBack()) {
webview.goBack();
}
else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView view = (WebView) findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyCustomWebViewClient());
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("http://url");
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.imageLoading1).setVisibility(View.GONE);
//show webview
findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (view.canGoBack()) {
view.goBack();
} else {
view.loadUrl("file:///android_asset/index.html");
}
Toast.makeText(getBaseContext(), description, Toast.LENGTH_LONG).show();
}
}
}
Just because your webView is null. You are not referencing it anywhere. Modified your code.
public class MainActivity extends AppCompatActivity {
private WebView view;
/** Called when the activity is first created. */
public void onBackPressed (){
if (view.isFocused() && view.canGoBack()) {
view.goBack();
}
else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (WebView) findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyCustomWebViewClient());
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("http://url");
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.imageLoading1).setVisibility(View.GONE);
//show webview
findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (view.canGoBack()) {
view.goBack();
} else {
view.loadUrl("file:///android_asset/index.html");
}
Toast.makeText(getBaseContext(), description, Toast.LENGTH_LONG).show();
}
}
}
In onCreate you have:
WebView view = (WebView) findViewById(R.id.webView);
The WebView you have defined at the top has not been initialized, and is the one being used by the onBackPressed method, to fix this all you need to do is remove WebView before initializing the variable in onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (WebView) findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyCustomWebViewClient());
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("http://url");
}
Actually you can not do directly inside the fragment. The onBackPressed can be overridden in the FragmentActivity. What you can do is:
1.Override the onBackPressed inside the activity.
2.When the onBackPressed is called, check if the instance of the current fragment is the instance showing the webview.
3.If it is, ask the fragment if the webview can go back.
4.If it is not, call the super or whatever you need
#Override
public void onBackPressed() {
Fragment webview = getSupportFragmentManager().findFragmentByTag("webview");
if (webview instanceof MyWebViewFragment) {
boolean goback = ((MyWebViewFragment)webview).canGoBack();
if (!goback)
super.onBackPressed();
}
}

Sharing image from webview to whatsapp

I have created an app which shows multiple webpages. I want that app to share image which is displayed on that webpage with whatsapp and other IM messengers, for that i have added a context menu and have implemented ACTION_SEND but it didn't work. When i try to share image it gives me error "sharing failed please try again" Here is my code
public class TopRatedFragment extends Fragment {
private ProgressBar progress;
private WebView myWebView2;
private Menu optionsMenu;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
String url = "http://images.google.com";
myWebView2 = (WebView) rootView.findViewById(R.id.webViewTop);
myWebView2.setWebChromeClient(new myWebViewClient());
myWebView2.getSettings().setJavaScriptEnabled(true);
progress = (ProgressBar) rootView.findViewById(R.id.progressBar3);
progress.setMax(100);
setHasOptionsMenu(true);
myWebView2.loadUrl(url);
myWebView2.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView View, String url) {
View.loadUrl(url);
TopRatedFragment.this.progress.setProgress(0);
return true;
}
});
myWebView2.setOnKeyListener(new android.view.View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return rootView;
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
optionsMenu = menu;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.airport_menuRefresh:
TopRatedFragment.this.myWebView2.reload();
setRefreshActionButtonState(true);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, v.getId(), 0, "Call");
menu.add(0, v.getId(), 0, "share image");
}
#Override
public boolean onContextItemSelected(MenuItem item){
if(item.getTitle()=="Call"){
Toast.makeText(getActivity(), "calling code", Toast.LENGTH_LONG).show();
}
else if(item.getTitle()=="share image")
{
// This is the code which i am using for share intent
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageState()));
startActivity(Intent.createChooser(share, "Share image using"));
}else{
return false;
}
return true;
}
Thanks for your help!
This line looks strange
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageState()));
The stream extra is supposed to contain the uri to the image you want to share, but you are setting it to something I don't even understand what it's supposed to do - that wouldn't even evaluate to a uri.
Currently you are not supplying the intent with any information on WHAT content you want to send. Set the stream extra to the image location uri and you should be fine.
(Btw you really should compare strings using equals() rather than ==. And you shouldn't identify menu item on titles as it would fail when localized etc. Use the menu item id.)

display Interstitial onclick or open url

i want to display Interstitial onclick or open url ..
in webview
plz help me
my ShowWebViev.java :
public class ShowWebView extends Activity {
//private Button button;
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_web_view);
AdView mAdView = (AdView) findViewById(R.id.adView );
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
//Get webview
webView = (WebView) findViewById(R.id.webView1);
startWebView("http://MYsite");
}
public class ShowWebView extends Activity {
private InterstitialAd interstitial;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_web_view);
// Create the interstitial.
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId("ca-app-pub-555555555555555/12334567890");
// Create ad request.
AdRequest adRequest = new AdRequest.Builder().build();
// Begin loading your interstitial.
interstitial.loadAd(adRequest);
}
// Invoke displayInterstitial() when you are ready to display an interstitial.
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}
private void startWebView(String url) {
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("rtmp:") | url.endsWith(".m3u8") | url.startsWith("http://212.35.75.130")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setComponent(new ComponentName("com.xmtvplayer.watch.live.streams", "org.zeipel.videoplayer.XMTVPlayer"));
intent.setData(Uri.parse(url));
intent.putExtra("secure_uri", true);
startActivity(intent);
return true;
} else{
Toast.makeText(getApplicationContext(), "tv", Toast.LENGTH_SHORT).show(); }
return false;
}
/*/Show loader on url load
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(ShowWebView.this);
progressDialog.setMessage("Loading... plz download XMTV Player To Watch Channel");
progressDialog.show();
}
}*/
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
startWebView("file:///android_asset/myerrorpage.html");
}
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
/*
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
*/
/*
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webView.loadData(summary, "text/html", null);
*/
//Load url in webview
webView.loadUrl(url);
webView.clearHistory();
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.ref){
webView.reload();
return true;
}
return super.onOptionsItemSelected(item);
}
Regarding docs of xmtv player, you can use startActivityForResult instead of startActivity. You can call your Interstitial Ad on event onActivityResult.
public void XMTVPlayerPlayUri(String Title,String uri){
// [String] adszone - get zone id after filling form.
// [Integer] adstime - how long ad will stay before user will able to close it, value is in seconds.
Bundle bnd = new Bundle();
bnd.putString("path", uri);
bnd.putString("name", Title);
bnd.putString("adszone", "15E56089-CB15-4AA7-8D1B-574E899DE009"); // change adszone with your own id.
bnd.putInt("adstime",30);
Intent intent = new Intent();
intent.setClassName("com.xmtvplayer.watch.live.streams","org.zeipel.videoplayer.XMTVPlayer");
intent.putExtras(bnd);
startActivityForResult(intent, 100);
}

onBackPressed() doesn't work for me

I have a problem, which is also discussed here:
onBackPressed never gets called
I'm trying to cancel a CountDownTimer when pressing the native back button from an android phone. So I would like to overrite the onBackPressed method, to cancel the timer and return to another activity, but only once. (to return to the main activity, like a home button).
This is a part of the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (getResources().getConfiguration().orientation== Configuration.ORIENTATION_LANDSCAPE){
ImageView und1=(ImageView)findViewById(R.id.undita1);
ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) und1.getLayoutParams();
params.height=150;
und1.setLayoutParams(params);
ImageView und2=(ImageView)findViewById(R.id.undita2);
ViewGroup.LayoutParams params2 = (ViewGroup.LayoutParams) und2.getLayoutParams();
params2.height=150;
und2.setLayoutParams(params2);
ImageView und3=(ImageView)findViewById(R.id.undita3);
ViewGroup.LayoutParams params3 = (ViewGroup.LayoutParams) und3.getLayoutParams();
params3.height=150;
und3.setLayoutParams(params3);
}
mProgressBar=(ProgressBar)findViewById(R.id.progressBar);
mProgressBar.setProgress(0);
mCountDownTimer=new CountDownTimer(90000,1000) {
int i=0;
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + i + millisUntilFinished);
i++;
mProgressBar.setProgress(i); }
#Override
public void onFinish() {
i++;
mProgressBar.setProgress(i);
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
}
};
mCountDownTimer.start();
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Bundle b;
b = getIntent().getExtras();
nivel= b.getInt("level");
TextView niv=(TextView) findViewById(R.id.Nivel);
niv.setText("Level: "+ nivel);
generare_3_diferente(nivel);}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
mCountDownTimer.cancel();
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
mCountDownTimer.cancel();
return true;
}else{
return super.onKeyDown(keyCode, event);
}
}
#Override
public void onBackPressed(){
mCountDownTimer.cancel();
Intent in = new Intent(this, MyActivity2.class);
startActivity(in);
super.onBackPressed();
}
}
the onBackPressed should be in the main activity class
Also try to specify the parent and child activities in the manifest file of the app e.g
android:parentActivityName
and try to use something like this and rebuild your App
#Override
public void onBackPressed() {
super.onBackPressed();
i = new Intent(CurrentActivity.this, NextActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
if it still doesn't work try to make a new application and import your files

Categories