How can i play videos in webview android? - android

Since im quite new to Java and Android apps, i had to ask this question because im working for 10 hours and couldnt achive anything. I made a full screen web app in eclipse but i cant see videos in there. Here's my codes:
Tarim.java
package com.tarim.tarimvideo;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import com.tarim.tarimvideo.util.SystemUiHider;
#SuppressLint("SetJavaScriptEnabled")
public class Tarim extends Activity {
private static final boolean AUTO_HIDE = true;
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
private static final boolean TOGGLE_ON_CLICK = true;
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
private SystemUiHider mSystemUiHider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tarim);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
WebView webView = (WebView)findViewById(R.id.tarayici);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.youtube.com/watch?v=W8SCqLkHDqw");
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tarim.tarimvideo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.tarim.tarimvideo.Tarim"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:theme="#style/FullscreenTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity.tarim.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0099cc"
tools:context=".Tarim" >
<!--
The primary full-screen view. This can be replaced with whatever view
is needed to present your content, e.g. VideoView, SurfaceView,
TextureView, etc.
-->
<TextView
android:id="#+id/fullscreen_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:keepScreenOn="true"
android:text="#string/dummy_content"
android:textColor="#33b5e5"
android:textSize="50sp"
android:textStyle="bold" />
<!--
This FrameLayout insets its children based on system windows using
android:fitsSystemWindows.
-->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true" >
<LinearLayout
android:id="#+id/fullscreen_content_controls"
style="?buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:background="#color/black_overlay"
android:orientation="horizontal"
tools:ignore="UselessParent" >
<Button
android:id="#+id/dummy_button"
style="?buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/dummy_button" />
</LinearLayout>
<WebView
android:id="#+id/tarayici"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</FrameLayout>
Please note that im in this Java thing just for 10 hours, so if you can explain me as much as simple, it would be so great.

It does not look like it is possible in a WebView without the assistance of flash. Please look at this: Youtube in a webview (used for reference). And look at this for a flash demo: Flash demo. Lastly this might also be helpful, it is Android's YouTube API.

Just put a .html file in your SDCARD which contain your video link.(mention video link as content:\\).and load that .html file to the webview.

Related

AccessibilityEvents not being caught by service on Activity start

I'm trying to have my app announce some information to my custom AccessibilityService when the user starts an Activity. I have a TextView that calls requestFocus() when the activity starts, and then I send an AccessibilityEvent to have the AccessibilityService read the TextView's content description. I've isolated the problem into a small application.
Here's the main Activity:
package com.example.ttstest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View v = findViewById(R.id.textView1);
v.requestFocus();
v.sendAccessibilityEvent(AccessibilityEvent.TYPE_ANNOUNCEMENT);
}
}
The layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ttstest.MainActivity" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:contentDescription="Secondarily focused text view"
android:text="#string/hello_world" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_marginLeft="54dp"
android:layout_marginTop="145dp"
android:layout_toRightOf="#+id/textView2"
android:contentDescription="Initially focused text view"
android:focusable="true"
android:focusableInTouchMode="true"
android:text="Initially focused text view" />
</RelativeLayout>
And the AccessibilityService:
package com.example.ttstest;
import android.accessibilityservice.AccessibilityService;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
public class TextToSpeechService extends AccessibilityService {
private static TextToSpeech textToSpeech = null;
private static boolean ttsReady = false;
#Override
protected void onServiceConnected() {
super.onServiceConnected();
Log.e("TextToSpeechService", "Got to onServiceConnected()");
textToSpeech = new TextToSpeech(this.getApplicationContext(), new OnInitListener() {
#Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS) {
ttsReady = true;
}
}
});
}
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
Log.e("TextToSpeechService", "Entering onAccessibilityEvent().");
Log.e("TextToSpeechService", "Event type: " + event.getEventType() + ", from class " + event.getClassName());
if(event.getContentDescription() != null) {
Log.e("TextToSpeechService", "" + event.getContentDescription());
}
if(textToSpeech != null && ttsReady == true) {
if(event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED) {
CharSequence contentDescription = event.getContentDescription();
if(contentDescription != null) {
String say = contentDescription.toString();
textToSpeech.speak(say, TextToSpeech.QUEUE_FLUSH, null);
}
} else if (event.getEventType() == AccessibilityEvent.TYPE_ANNOUNCEMENT) {
CharSequence contentDescription = event.getContentDescription();
if(contentDescription != null) {
textToSpeech.speak(event.getContentDescription().toString(), TextToSpeech.QUEUE_FLUSH, null);
}
}
}
Log.e("TextToSpeechService", "Exiting onAccessibilityEvent().");
}
#Override
public void onInterrupt() {
Log.e("TextToSpeechService", "Entering onInterrupt()");
if(textToSpeech != null && ttsReady == true) {
textToSpeech.stop();
}
}
}
This has been added to my AndroidManifest.xml in the appropriate location:
<service android:name="com.example.ttstest.TextToSpeechService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" >
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data android:name="android.accessibilityservice"
android:resource="#xml/accessibilityservice"/>
</service>
My accessibilityservice.xml settings:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeAllMask"
android:notificationTimeout="100"
android:accessibilityFeedbackType="feedbackSpoken"
android:accessibilityFlags="flagDefault"
android:canRetrieveWindowContent="true"
android:packageNames="com.example.ttstest"/>
And finally, the problem. When I first start the application, neither the TextView gaining focus from requestFocus() or the call to sendAccessibilityEvent() actually send anything to the AccessibilityService. If I tab through the TextViews by attaching a physical keyboard, the focus events are received. I have made sure to turn on the AccessibilityService in the settings, and I have proof from the application I made this example from that the AccessibilityService is enabled when requestFocus() and sendAccessibilityEvent() are called. This doesn't help. It seems like when an Activity is first started, neither of these methods send anything to the AccessibilityService. I've also tried calling announceForAccessibility() with similar results.
Am I doing this wrong? How can I fix it, or at least get around it? Specifically, I want to send an event to my AccessibilityService when an Activity first starts.
More information: I have tried moving the requestFocus() and sendAccessibilityEvent() calls to onStart() and onWindowFocusChanged(); neither of these work either.
I may be mistaken but the "UI" isn't ready until onResume() is called so perhaps that is the issue?

Issue with full screen apk

I've just wrote my first android application, but I got a so sneaky problem :D.
The application is so simple, it has just one text box, one button and one web view.
The web view is invisible, when the button is clicked it will be visible and go to the url written in the text box
the application is full screen.
The problem is that when I click the button it does nothing at first, the second time it works.
So as I know there is a focus problem, I think, i just themed it with
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
so there is no title bar at top. I remember that when I had title bar these acts took place
1 - I click on button
2 - the title bar appears
3 - I click on button
4 - it took affect
I can say that when I make title bar invisible, steps are the same as top.
So i need help to solve this problem, any ideas?
activity_fullscreen.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0099cc"
tools:context=".FullscreenActivity">
<!-- The primary full-screen view. This can be replaced with whatever view
is needed to present your content, e.g. VideoView, SurfaceView,
TextureView, etc. -->
<!-- This FrameLayout insets its children based on system windows using
android:fitsSystemWindows. -->
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#ff3191ff">
<LinearLayout android:id="#+id/fullscreen_content_controls"
style="?metaButtonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:background="#color/black_overlay"
android:orientation="horizontal"
tools:ignore="UselessParent">
</LinearLayout>
</FrameLayout>
<AutoCompleteTextView android:id="#+id/iptxt"
android:layout_width="272dp" android:layout_height="59dp"
android:nextFocusUp="#id/iptxt" android:nextFocusLeft="#id/iptxt"
android:layout_gravity="center"
android:textColor="#ff26b9ff"
android:textSize="10pt"
android:text="192.168.1.104"
android:textAlignment="center"
android:textStyle="bold"
android:singleLine="true"
android:typeface="normal"
android:inputType="text" />
<Button
android:layout_width="fill_parent"
android:layout_height="59dp"
android:id="#+id/ConnectBTN"
android:layout_gravity="bottom"
android:background="#ff3191ff"
android:text="Connect"
android:textColor="#ffffffff"
android:textSize="12pt"
android:textStyle="bold" />
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/Mainwbv"
android:visibility="invisible"></WebView>
</FrameLayout>
androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.proapp.share" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
<activity
android:name=".FullscreenActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:screenOrientation="portrait"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
fullscreenactivity.java
package ir.proapp.share;
import ir.proapp.share.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import org.apache.http.protocol.RequestUserAgent;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class FullscreenActivity extends Activity {
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content_controls);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
Button connectbtn=(Button)findViewById(R.id.ConnectBTN);
connectbtn.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
EditText iptetx=(EditText)findViewById(R.id.iptxt);
WebView maniWV=(WebView)findViewById(R.id.Mainwbv);
WebSettings mainSettings=maniWV.getSettings();
mainSettings.setJavaScriptEnabled(true);
mainSettings.setUserAgentString("Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31
(KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31");
maniWV.setVisibility(View.VISIBLE);
maniWV.setWebViewClient(new Ac1());
maniWV.loadUrl("http://"+iptetx.getText()+":9999");
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
/* findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener); */
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
}

Android Main activity with 2 button to open the 2nd activity in webview

Hi I am new to android.
My main activity has show 2 buttons. If user click button 1 it to open google website in webview and for button 2 to open yahoo website in webview. I do not want open in any other browser.
Here is my code; but it is not working can any one please tell me what am I doing wrong here.
package com.jo.mavselect;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class SelectRm extends Activity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_rm);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.select_rm, 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);
}
/** Called when the user clicks the Send button */
public void sendMessage(View v) {
if(v.getId()==R.id.B9)
{
message ="www.google.com.au";
}
else
if(v.getId()==R.id.B10)
{
message ="www.google.com.au";
}
Intent intent = new Intent(this, MavisActivity.class);
intent.putExtra("msg",message);
startActivity(intent);
}
}
**MavisActivity **
package com.jo.mavselect;
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;
import android.content.Intent;
public class MavisActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebView = new WebView(this);
setContentView(mWebView);
mWebView =(WebView) findViewById(R.id.Webview);
mWebView.setWebViewClient(new WebViewClient());
// web page to fit to the screen
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
// Not to cache
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.getSettings().setAppCacheEnabled(false);
// Enable Java script
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// No to cache
mWebView.clearCache(true);
//Clears any saved data for web forms.
mWebView.clearFormData();
//Tells this WebView to clear its internal back/forward list.
mWebView.clearHistory();
Intent intent = getIntent();
String ur = intent.getExtras().getString("msg");
mWebView.loadUrl(ur);
final Activity activity = this;
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mWebView.loadUrl("file:///android_asset/error.html");
}
});
}
}
manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jo.mavselect" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.jo.mavselect.MavisActivity"
android:label="MavisActivity"
android:parentActivityName="com.jo.mavselect.SelectRm" >
// android:label="#string/app_name" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.jo.mavselect.SelectRm" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
activity xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".SelectRm/">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Goole"
android:id="#+id/B9"
android:layout_marginTop="60dp"
android:layout_alignParentTop="true"
android:onClick="sendMessage" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yahoo"
android:id="#+id/B10"
android:layout_toEndOf="#+id/B9"
android:layout_marginLeft="84dp"
android:layout_alignTop="#+id/B9"
android:layout_toRightOf="#+id/B9"
android:onClick="sendMessage" />
<WebView
android:id="#+id/Webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
You make totally wrong way.
You should try to fix your layout. Remove this line code mWebView = new WebView(this);
setContentView(mWebView); And replace with setContentView(R.layout.activity_xml); In xml file add this line code in your web view element. android:layout_below="#id/B9"
You must add onClickListener method for those buttons. In this listener set what page to open with web view.
Add method in your activity class:
public void sendMessage(View v)
{
if(v.getId() == R.id.B9){
mWebView.loadUrl("http://www.google.com");
}
if(v.getId() == R.id.B10) {
mWebView.loadUrl("http://www.yahoo.com");
}
}

How to get the SeekBar work to adjust brightness

First of all, I am new to Android Developing so don't be so harsh on me.
I have tried to get the SeekBar to adjust the brightness level of either the application or the entire system. Although, I have not been able to get this to work.
My XML-file looks like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SettingsPage" >
<SeekBar
android:id="#+id/seekBar2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/seekBar"
android:layout_below="#+id/seekBar"
android:layout_marginTop="30dp" />
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="21dp"
android:max="100"
android:progress="50" />
</RelativeLayout>
XML code for MainActivity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/buttonSettings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Button"
android:onClick="settingsPage"/>
</RelativeLayout>
XML code, the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testsetup"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.testsetup.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.testsetup.SettingsPage"
android:label="#string/title_activity_settings_page" >
</activity>
<activity
android:name="com.example.testsetup.BrightnessAdjuster"
android:label="#string/title_activity_brightness_adjuster" >
</activity>
<activity
android:name="com.example.testsetup.BrightnessActivity"
android:label="#string/title_activity_brightness" >
</activity>
</application>
</manifest>
My Java-code that I have looks like this:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SettingsPage extends Activity {
float BackLightValue = 0.5f; // dummy default value
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_page);
SeekBar BackLightControl = (SeekBar) findViewById(R.id.action_settings);
BackLightControl
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener());
}
public void onClick(View arg0) {
int SysBackLightValue = (int) (BackLightValue * 255);
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS,
SysBackLightValue);
}
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
BackLightValue = (float) arg1 / 100;
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.screenBrightness = BackLightValue;
getWindow().setAttributes(layoutParams);
}
public void onStartTrackingTouch(SeekBar arg0) {
}
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings_page, menu);
return true;
}
}
Java code for MainActivity
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
public void settingsPage(View view){
Intent intent = new Intent(this, SettingsPage.class);
startActivity(intent);
}
}
The problem is that I do not know if this is the right way, even though I have tried to follow several guides on the matter.
Also, I get one error in the above code, and it is the following line
BackLightControl
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener());
I get the error that "cannot instantiate type SeekBar.OnSeekBarChangeListener()".
I thought it was due to the fact that OnSeekBarChangeListener was an interface, so I tried to create a random class that implemented OnSeekBarChangeListener and instantiate that class, but that did not work either.
So, now is my question; how to proceed from here?
Regards and thanks in advance
Erik
EDIT
Added my other classes and XML files. Plus, I no longer get the error on the line with instantiating the OnSeekBarChangeListener thing.
Regards
Erik
You cannot in instantiate OnSeekBarChangeListener because it's an interface. If you create a class which implements this interface, and use an instance of that class as the parameter of setOnSeekBarChangeListener, that should definitely work. The easiest way is letting your Activity implement OnSeekBarChangeListener, and pass this to the setter method.
public class SettingsPage extends Activity implements SeekBar.OnSeekBarChangeListener {
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_page);
SeekBar BackLightControl = (SeekBar) findViewById(R.id.action_settings);
BackLightControl.setOnSeekBarChangeListener(this);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// ...
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// ...
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// ...
}
// ...
}
Side note: you should use standard Java naming conventions, variable names start with lowercase characters.

Android application restarts when opened by clicking the application icon

I am new to the Android development world and I've built a simple "Hello World" app. First, activity requests a text. When the "Go" button is clicked, the app launches the second activity displaying the input text.
If I click the HOME button and then click the application icon, the app launches the first activity again but if I press-hold the home button and click the icon from the "Recent apps" bar, it resumes the app where I left.
How do I avoid this?
I need my app to resume even if the launcher icon is clicked.
MainActivity.java,
package com.example.myfirstandroidapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view){
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.txtName);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayActivity.java,
package com.example.myfirstandroidapp;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
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.display_message, menu);
return true;
}
#Override
public void onDestroy(){
super.onDestroy();
}
#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);
}
}
activity_main.xml,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btnGo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/txtName"
android:layout_alignParentRight="true"
android:onClick="sendMessage"
android:text="Go!" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtName"
android:layout_alignParentTop="true"
android:layout_marginTop="18dp"
android:text="Please input your name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
activity_display_message.xml,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".DisplayMessageActivity" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
AndroidManifest.xml,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstandroidapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myfirstandroidapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.myfirstandroidapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstandroidapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstandroidapp.MainActivity" />
</activity>
</application>
</manifest>
Problem:
I'm not qualified to say this a bug, but there is a behaviour with release builds when starting the application from the launcher. It seems that instead of resuming the previous Activity, it adds a new Activity on top. There is a related bug report on this topic here.
Solution:
I'm working around this this by closing the Launcher Activity if it's not the root of the task, as a result the previous Activity in that task will be resumed.
if (!isTaskRoot()) {
finish();
return;
}
Issue for me was whenever app in installed by an apk with the click on 'Open' option it used to relaunch every time when we minimize it.
resolved it by
SplashActivity.java:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!isTaskRoot
&& intent.hasCategory(Intent.CATEGORY_LAUNCHER)
&& intent.action != null
&& intent.action.equals(Intent.ACTION_MAIN)) {
finish()
return
}
}

Categories

Resources