My give URL doesn't load with this code, however if I press 'home' key and click on app icon again(ie. resuming my activity) then it loads. I tried looking into activity lifecycle, tinkered with code but still it doesn't work. Please let me know if I need to clarify my question further. Thanks.
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.SslError;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView.SavedState;
import android.widget.Toast;
import com.ABC.R;
import com.ABC.util.CustomProgressDialogs;
import com.ABC.util.DeviceCheck;
import com.ABC.util.GlobalFunction;
import com.ABC.util.HTML5WebView;
import com.ABC.util.KeyBoard;
import com.ABC.util.NetworkCheck;
public class CanvasActivity extends Activity {
private HTML5WebView mWebView;
private ProgressDialog webPageDialog;
private Context context;
private GlobalFunction globalFunc;
private KeyBoard keyBoard;
private BroadcastReceiver connectionReceiver;
String myUrl;
SharedPreferences prefs;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Log.d("killapp", "killapp");
globalFunc.killApplication(context);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog exitDialog = builder.create();
exitDialog.show();
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = CanvasActivity.this;
mWebView = new HTML5WebView(context);
// setContentView(mWebView.getLayout());
final DeviceCheck deviceCheck = new DeviceCheck(context); // change
// mWebView = new HTML5WebView(this);
// getWindow().requestFeature(Window.);
// setContentView()
// getWindow().
setContentView(mWebView.getLayout());
globalFunc = new GlobalFunction();
webPageDialog = new ProgressDialog(context);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Log.d("onReceivedError", failingUrl + " " + errorCode);
mWebView.loadUrl("file:///android_asset/myerrorpage.html");
}
#Override
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
super.onReceivedSslError(view, handler, error);
Log.d("onReceivedSslError", "ssl error");
handler.proceed();
// To supercede SSL certificate error.
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d("page started", "page loading started");
webPageDialog.show();
webPageDialog.setContentView(CustomProgressDialogs
.iphoneProgressDialog(context));
webPageDialog.setCancelable(true);
// change
webPageDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
webPageDialog.dismiss();
globalFunc.killApplication(context);
}
});
}
#Override
public void onPageFinished(final WebView view, final String url) {
Log.i("onPageFinished", "onPageFinished");
if (webPageDialog.isShowing()) {
webPageDialog.dismiss();
}
}
});
if (getIntent().getStringExtra("Message") != null) {
Toast.makeText(getApplicationContext(),
getIntent().getIntExtra("push details", 0) + "",
Toast.LENGTH_LONG).show();
}
keyBoard = new KeyBoard(mWebView, context);
mWebView.addJavascriptInterface(keyBoard, "KeyBoard");
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
/*
* if(prefs.getString("url",
* getResources().getString(R.string.MYURL_URL)).trim().equals("")){
* myUrl=getResources().getString(R.string.MYURL_URL).trim(); }else{
* myUrl = prefs.getString("url",
* getResources().getString(R.string.MYURL_URL)).trim(); }
* mWebView.loadUrl(myUrl);
*/
myUrl = getResources().getString(R.string.MYURL_URL).trim();
/*
* if (!myUrl.equalsIgnoreCase(prefs.getString("url",
* getResources().getString(R.string.MYURL_URL)).trim())) {
*
* myUrl = prefs.getString("url",
* getResources().getString(R.string.MYURL_URL)).trim();
*
* }
*/
// mWebView.loadUrl(myUrl);
if (new NetworkCheck(context).isOnline()) {
// change
webPageDialog.show();
webPageDialog.setContentView(CustomProgressDialogs
.iphoneProgressDialog(context));
webPageDialog.setCancelable(true);
webPageDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
webPageDialog.dismiss();
globalFunc.killApplication(context);
}
});
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
} else {
mWebView.loadUrl(myUrl);
/*
* if (deviceCheck.isTablet()) {
* setRequestedOrientation(ActivityInfo
* .SCREEN_ORIENTATION_LANDSCAPE); mWebView.loadUrl(myUrl); }
* else {
* setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
* ); mWebView.loadUrl(myUrl); }
*/
}
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
mWebView.loadUrl(myUrl);
}
#Override
public void onResume() {
super.onResume();
if (!((prefs.getString("url",
getResources().getString(R.string.MYURL_URL)).trim()))
.equals("")) {
myUrl = prefs.getString("url",
getResources().getString(R.string.MYURL_URL)).trim();
}
if (!(myUrl.equals(mWebView.getUrl()))) {
// mWebView.loadUrl(myUrl);
}
/*
* if (!mWebView.getUrl().equalsIgnoreCase(prefs.getString("url",
* getResources().getString(R.string.MYURL_URL)).trim())) {
*
* myUrl = prefs.getString("url",
* getResources().getString(R.string.MYURL_URL)).trim();
* mWebView.loadUrl(myUrl); }
*/
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("CanvasActivity-onOptionsItemSelected", "in option selected");
switch (item.getItemId()) {
case R.id.url:
startActivity(new Intent(this, EditURL.class));
return true;
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
Log.d("CanvasActivity-onCreateOptionsMenu",
"in oncreate option menu");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menuxml, menu);
return true;
}
#Override
public void onStop() {
super.onStop();
mWebView.stopLoading();
}
// onkeydown was here.
public void startBroadcastService() {
connectionReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
ConnectivityManager connManager1 = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mMobile = connManager1
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isNoNetwork = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (!isNoNetwork) {
if (mWifi.isAvailable()) {
}
if ((mWifi.isConnected() && mWifi.isAvailable())
|| (mMobile.isConnected() && mMobile.isAvailable())) {
if (mWebView.getUrl().contains("myerrorpage")) {
mWebView.loadUrl(myUrl);
}
}
}
}
};
registerReceiver(connectionReceiver, new IntentFilter(
"android.net.conn.CONNECTIVITY_CHANGE"));
}
}
I created a handler and loaded my URL after my webview is registered in that handler with relevent functions( onPageStarted onPageFinished and onReceivedError) , because my webview was taking much time to load the page. This worked.
handler = new Handler();
jsInterface = new JSInterface(mWebView, context, uniqueGeneratedkey,
handler);
handler.post(new Runnable() {
#Override
public void run() {
jsInterface.initiateProcess();
/*where initiateProcess() is the method where I register all the overridden
*functions ie. OnPageStarted() and OnPageFinished();
*/
}
});
mWebview.LoadUrl(url);
Related
I'm having a problem with my WebView-App.
I want to add a "Connection-check" on startup that's popping up an error when no Internet-connection is aviable or the WebView is timed out. I can't get it done by myself because I'm new in Android-programming.
I also want to add an options-menu where i can reload the actual page.
Hope someone can help me...
The actual code:
package com.sabithpkcmnr.webviewmaster;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ImageView superImageView;
ProgressBar superProgressBar;
WebView superWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(true);
superImageView = findViewById(R.id.myImageView);
superProgressBar = findViewById(R.id.myProgressBar);
superWebView = findViewById(R.id.myWebView);
superProgressBar.setMax(100);
superWebView.loadUrl("http://google.com");
superWebView.getSettings().setJavaScriptEnabled(true);
superWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
superWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
superProgressBar.setProgress(newProgress);
}
#Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
getSupportActionBar().setTitle(title);
}
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
superImageView.setImageBitmap(icon);
}
});
superWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Uri myUri = Uri.parse(url);
Intent superIntent = new Intent(Intent.ACTION_VIEW);
superIntent.setData(myUri);
startActivity(superIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater myMenuInflater = getMenuInflater();
myMenuInflater.inflate(R.menu.super_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.myMenuOne:
onBackPressed();
break;
case R.id.myMenuTwo:
GoForward();
break;
case R.id.myMenuThree:
break;
}
return true;
}
private void GoForward() {
if (superWebView.canGoForward()) {
superWebView.goForward();
} else {
Toast.makeText(this, "Can't go further!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
if (superWebView.canGoBack()) {
superWebView.goBack();
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("(Exit?");
dialog.setMessage("Name has nothing to go back, so what next?");
dialog.setPositiveButton("EXIT ME", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setCancelable(false);
dialog.setNegativeButton("STAY HERE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
}
Try below method by replacing your setWebViewClient,
superWebView= (WebView) findViewById(R.id.webView);
superWebView.setWebViewClient(new myWebClient());
superWebView.getSettings().setJavaScriptEnabled(true);
superWebView.loadUrl("LOAD_YOUR_URL");
superWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}
});
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Below method can be used to check internet connection.
public static boolean checkInternetConnection(Context context) {
ConnectivityManager con_manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (con_manager.getActiveNetworkInfo() != null
&& con_manager.getActiveNetworkInfo().isAvailable()
&& con_manager.getActiveNetworkInfo().isConnected());
}
you can check internet connection before loading url in webview.
Check below code snippet.
if (checkInternetConnection(this)) {
superWebView.loadUrl("http://google.com");
}else{
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
}
I am trying to understand how this stuff works a little better.
So I learned about Runnables and Threads and ASyncTasks but apparently they have some serious drawbacks when it comes to configuration changes like rotating the screen.
Is it better to instead use IntentService for anything that should run in the background like SQL database commands, file-system procedures, Internet input/output processes, etc -- and then use LocalBroadcastReceiver to pass results back to the Activity?
Is it better to instead use IntentService for anything that should run in the background like SQL database commands, file-system procedures, Internet input/output processes, etc -- and then use LocalBroadcastReceiver to pass results back to the Activity?
A service is needed if your UI might move to the background while the work is going on, and you are concerned that your process might be terminated while the work is going on. I tend to only worry about this if the work might exceed a second or so. Otherwise, a plain thread suffices.
Using an event bus, like LocalBroadcastManager, is a reasonable approach to let other components know when your service/thread is done with its work. This sample app demonstrates this. Personally, I tend to use greenrobot's EventBus — this sample app is a clone of the first one, but using EventBus instead of LocalBroadcastManager.
Follow an example of a chat using one activity (chat activity) that run a class in service (realtime class). I use a mvc webapi to controll chat between chatters. When realtime receive a message "onConnected" or "ReceivedMessageServer" automatically send by LocalBroadcastManager to chat activity. This way in "onReceive" from BroadcastReceiver receives the message and runs other tasks.
a) ChatActivity.class
package br.com.yourapp;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Calendar;
import br.com.yourapp.model.MessageReceived;
import util.RealTime;
public class ChatActivity extends AppCompatActivity implements View.OnClickListener,
View.OnKeyListener , TextWatcher {
AppController obj;
private ProgressDialog pDialog;
MediaPlayer mp;
private ListView lstChatLog;
private ArrayAdapter<String> listAdapter;
private EditText txtChatMessage;
private TextView lblTyping;
private Button btnSendChat;
private boolean resultRequest = true;
private String errorMessage = "Internet is not working";
private AlertDialog alertDialog;
private AlertDialog.Builder alertBuilder;
String userType = "V";
String spaces = "\u0020\u0020\u0020\u0020";
Calendar time;
MessageReceived msg;
private RealTime realTime;
private final Context mContext = this;
private boolean mBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
showProgressDialog();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
obj = (AppController) getApplicationContext();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
lblTyping = (TextView) findViewById(R.id.lblTyping);
txtChatMessage = (EditText) findViewById(R.id.txtChatMessage);
txtChatMessage.setOnKeyListener(this);
txtChatMessage.addTextChangedListener(this);
btnSendChat = (Button) findViewById(R.id.btnSendChat);
btnSendChat.setOnClickListener(this);
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Alert");
alertBuilder = new AlertDialog.Builder(this);
lstChatLog = (ListView) findViewById(R.id.lstChatLog);
listAdapter = new ArrayAdapter<String>(ChatActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setHeight(20);
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
return view;
}
};
Intent intent = new Intent();
intent.setClass(mContext, RealTime.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
IntentFilter filter = new IntentFilter("Connect");
filter.addAction("RecMsg");
LocalBroadcastManager.getInstance(ChatActivity.this).registerReceiver(mMessageReceiver, filter);
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().toString().equals("Connect")) {
msg = (MessageReceived) intent.getExtras().getParcelable("msg");
if (msg == null || msg.Message == null)
return;
listAdapter.add(msg.Destiny + "" + msg.CurrentTime + " : " + msg.Message);
lstChatLog.setAdapter(listAdapter);
realTime.SendToSpecific(msg.Sender, "Hi !", userType, obj.getRiderId(), obj.getDriverId());
hideProgressDialog();
}
else
if (intent.getAction().toString().equals("RecMsg")) {
msg = (MessageReceived) intent.getExtras().getParcelable("msg");
if (msg == null || msg.Message == null)
return;
if (msg.Message.equals("*0.+9=&!*#_&1|8%digi")) {
lblTyping.setVisibility(View.VISIBLE);
}
else
if (msg.Message.equals("*0.+9=&!*#_&1|8%"))
{
lblTyping.setVisibility(View.INVISIBLE);
}
else
{
lblTyping.setVisibility(View.INVISIBLE);
listAdapter.add(msg.Sender + "" + msg.CurrentTime + " : " + msg.Message);
lstChatLog.setAdapter(listAdapter);
mp = MediaPlayer.create(ChatActivity.this, R.raw.notify);
mp.setLooping(false);
mp.setVolume(100, 100);
mp.start();
}
}
}
};
private final ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
RealTime.LocalBinder binder = (RealTime.LocalBinder) service;
realTime = binder.getService();
mBound = true;
realTime.Connect(obj.getRiderName(), userType, obj.getRiderId(), obj.getLatitudeRider(), obj.getLongitudeRider(), obj.getDriverId(), obj.getVehicieId());
hideProgressDialog();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
#Override
protected void onStop() {
if (mBound) {
unbindService(mConnection);
mBound = false;
}
super.onStop();
}
public void SendToSpecific(String sender, String message, String userType, long userId, long operatorId) {
realTime.SendToSpecific(sender, message, userType, userId,operatorId);
if (!message.equals("*0.+9=&!*#_&1|8%digi") && !message.equals("*0.+9=&!*#_&1|8%"))
{
time = Calendar.getInstance();
listAdapter.add(spaces + sender + " " + "(" + time.get(Calendar.HOUR) + ":" + time.get(Calendar.MINUTE) + ")" + " : " + message);
lstChatLog.setAdapter(listAdapter);
txtChatMessage.setText("");
}
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_ENTER) {
if (txtChatMessage.getText().length() > 0)
{
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.
INPUT_METHOD_SERVICE);
if (this.getCurrentFocus() != null)
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
SendToSpecific(obj.getRiderName(), txtChatMessage.getText().toString(), userType, obj.getRiderId(), obj.getDriverId());
}
}
return false;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (txtChatMessage.getText().toString().length() > 0) {
if (txtChatMessage.getText().length() == 1) {
SendToSpecific(obj.getRiderName(), "*0.+9=&!*#_&1|8%digi", userType, obj.getRiderId(), obj.getDriverId());
}
} else {
SendToSpecific(obj.getRiderName(), "*0.+9=&!*#_&1|8%", userType, obj.getRiderId(), obj.getDriverId());
}
}
#Override
public void afterTextChanged(Editable s) {
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSendChat:
if (txtChatMessage != null && txtChatMessage.getText().length() > 0) {
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.
INPUT_METHOD_SERVICE);
if (this.getCurrentFocus() != null)
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
SendToSpecific(obj.getRiderName(), txtChatMessage.getText().toString(), userType, obj.getRiderId(), obj.getDriverId());
}
break;
}
}
private void showProgressDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideProgressDialog() {
if (pDialog.isShowing())
pDialog.hide();
}
#Override
protected void onDestroy() {
try {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
super.onDestroy();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.
INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null)
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
mMessageReceiver.clearAbortBroadcast();
Intent i = new Intent(this, MenuPageActivity.class);
obj.setLastActivity("Chat");
startActivity(i);
return true;
}
public void ShowAlert() {
hideProgressDialog();
if (resultRequest)
errorMessage = "Internet is not working";
alertBuilder.setTitle("Alert");
alertBuilder.setMessage(errorMessage);
alertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
});
alertDialog = alertBuilder.create();
alertDialog.show();
errorMessage = "";
resultRequest = true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}
b) Realtime.class
package util;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.util.concurrent.ExecutionException;
import br.com.yourapp.model.MessageReceived;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;
public class RealTime extends Service {
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private Handler mHandler;
private final IBinder mBinder = new LocalBinder();
public RealTime() { }
#Override
public void onCreate() {
super.onCreate();
mHandler = new Handler(Looper.getMainLooper());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int result = super.onStartCommand(intent, flags, startId);
startSignalR();
return result;
}
#Override
public void onDestroy() {
mHubConnection.stop();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
startSignalR();
return mBinder;
}
public class LocalBinder extends Binder {
public RealTime getService() {
return RealTime.this;
}
}
public void Connect(String userName, String userType, long userId, double latitude, double longitude, long driverId, long vehicleId) {
mHubProxy.invoke("Connect", userName, userType, userId, latitude, longitude, driverId, vehicleId);
}
public void SendMessageToGroup(String userName, String userGroup, String userType, long userId, double latitude, double longitude, long vehicleId, short option)
{
mHubProxy.invoke("SendMessageToGroup", userName, userGroup, userType, userId, latitude, longitude, vehicleId, option);
}
public void SendToSpecific(String sender, String message, String userType, long userId, long operatorId)
{
mHubProxy.invoke("SendToSpecific", sender, message, userType, userId, operatorId);
}
private void startSignalR() {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
mHubConnection = new HubConnection("http://webapi.com");
mHubProxy = mHubConnection.createHubProxy("ChatHub");
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException | ExecutionException e) {
Log.e("SimpleSignalR", e.toString());
return;
}
mHubProxy.on("onConnected",
new SubscriptionHandler1<MessageReceived>() {
#Override
public void run(final MessageReceived msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent = new Intent("Connect");
intent.putExtra("msg", msg);
LocalBroadcastManager.getInstance(RealTime.this).sendBroadcast(intent);
}
});
}
}
, MessageReceived.class);
}
}
mHubProxy.on("ReceivedMessageServer",
new SubscriptionHandler1<MessageReceived>() {
#Override
public void run(final MessageReceived msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent = new Intent("RecMsg");
intent.putExtra("msg", msg);
LocalBroadcastManager.getInstance(RealTime.this).sendBroadcast(intent);
}
});
}
}
, MessageReceived.class);
}
I have a ListActivity that implements OnScrollListener. Unfortunality the methods onScroll and onScrollStateChanged are never fired.
I have absolutly no idear why. The data is shown correctly. I am able to scroll inside my view... Do you see the problem?
package bc.qz.client.android.activity;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import bc.qz.client.android.R;
import bc.qz.client.android.adapter.ScoreListAdapter;
import bc.qz.client.android.proxy.RemoteServletCaller;
import de.bc.qz.business.Score;
public class ScoreActivity extends ListActivity implements OnScrollListener{
private SharedPreferences mSharedPreferences;
private RemoteServletCaller mRemoteServletCaller;
private Runnable lViewScoreRunnable;
private String mUuid;
private String mUsername;
private ProgressDialog mProgressDialog = null;
private ScoreListAdapter mScoreListAdapter;
List<Score> mAllScore = new ArrayList<Score>();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mRemoteServletCaller = new RemoteServletCaller();
mSharedPreferences = this.getSharedPreferences(
"de.bc.qz.client.sharedpreferences", Context.MODE_PRIVATE);
mUuid = mSharedPreferences.getString("uuid", null);
mUsername = mSharedPreferences.getString("user", null);
mScoreListAdapter = new ScoreListAdapter(this, mAllScore);
setListAdapter(mScoreListAdapter);
lViewScoreRunnable = new Runnable() {
#Override
public void run() {
loadAllScore(mUsername, mUuid);
}
};
Thread thread = new Thread(null, lViewScoreRunnable,
"MagentoBackground");
thread.start();
mProgressDialog = ProgressDialog.show(ScoreActivity.this,
"Bitte warten...", "Lade Highscore...", true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_score_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.goToTop:
return true;
case R.id.goToBottom:
return true;
case R.id.goToMine:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
System.out.println("onScroll");
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
System.out.println("onScrollStateChanged");
}
private void loadAllScore(String pUsername, String pUuid) {
try {
if (null == mUuid || mUsername == null) {
mUuid = UUID.randomUUID().toString();
mSharedPreferences.edit().putString("uuid", mUuid).commit();
mAllScore.addAll(mRemoteServletCaller.getAllScore(1, 50));
} else {
mAllScore.addAll(mRemoteServletCaller.getAllScore(mUsername,
mUuid));
}
} catch (Exception e) {
return;
}
runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if (mAllScore != null && mAllScore.size() > 0) {
mScoreListAdapter.notifyDataSetChanged();
for (int i = 0, N = mAllScore.size(); i < N; i++)
mScoreListAdapter.add(mAllScore.get(i));
}
mProgressDialog.dismiss();
}
};
}
getListView().setOnScrollListener(this);
I have a webview, yes i do. :)
Anyway, I load my main URL fine, but i need to load another url programmatically at some point. The problem is that it somewhat opens another webview, and I know this because when I exit the app using finish() method, the webview with the latter url closes, but another webview stays open. What should I do? Should i call destroy webview or something else?
I just load them URLs using webview.loadUrl(url here) method.
Here's what's inside my main activity:
package com.sample;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity
{
private WebView wv;
private ProgressBar progress;
private static String mycaturl="*url 1*";
private static String helpurl="*url 2*";
private static String fbackurl="*url 3*";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
if (reachable(this))
{
Toast.makeText(this, "Reachable", Toast.LENGTH_SHORT).show();
buildwv( savedInstanceState, WebSettings.LOAD_DEFAULT, mycaturl );
}
else
{
Toast.makeText(this, "Unreachable", Toast.LENGTH_SHORT).show();
eolc( savedInstanceState );
}
}
#SuppressLint({ "SetJavaScriptEnabled" })
public void buildwv(Bundle sis, int load, String url)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
setContentView(R.layout.activity_main);
//assigning objects to variables
wv=(WebView) findViewById(R.id.wv);
wv.setWebViewClient( new wvc() );
progress=(ProgressBar) findViewById(R.id.progress);
//websettings
WebSettings ws = wv.getSettings();
ws.setAppCacheMaxSize( 100 * 1024 * 1024 ); // 100MB
ws.setAppCachePath( this.getCacheDir().getAbsolutePath() );
ws.setAllowFileAccess( true );
ws.setAppCacheEnabled( true );
ws.setJavaScriptEnabled( true );
ws.setCacheMode(load);
//if instance is saved, to catch orientation change
if(sis==null)
{ wv.loadUrl(url); }
}
public void eolc(final Bundle sis)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );
alertDialog.setTitle("Unreachable Host");
alertDialog.setMessage("Host is unreachable. Load from cache or exit.");
alertDialog.setIcon(R.drawable.tick);
//alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton( "Load from Cache", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to load cache.", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, mycaturl );
}
});
alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help. EOLC", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, helpurl );
}
});
alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.create();
alertDialog.show();
}
public void roe()
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );
alertDialog.setTitle("Connection Lost");
alertDialog.setMessage("Connection to host was lost. Restart and load cache or exit.");
alertDialog.setIcon(R.drawable.tick);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton( "Restart", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
Toast.makeText(getApplicationContext(), "You chose to restart and load cache.", Toast.LENGTH_SHORT).show();
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(i);
}
});
alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help. ROE", Toast.LENGTH_SHORT).show();
wv.stopLoading();
wv.loadUrl( helpurl );
}
});
alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.create();
alertDialog.show();
}
private class wvc extends WebViewClient
{
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
progress.setVisibility(View.VISIBLE);
if (url.contains(mycaturl))
{
WebSettings ws = wv.getSettings();
if ( !reachable(getApplicationContext()) )
{
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
roe();
}
else if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "loading cache coz not reachable", Toast.LENGTH_SHORT).show();
}
}
else
{
if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "Connection to server established.", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
Toast.makeText(getApplicationContext(), "PAGE DONE LOADING!!", Toast.LENGTH_SHORT).show();
//circular progress bar close
progress.setVisibility(View.GONE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
super.onReceivedError(view, errorCode, description, failingUrl);
wv.stopLoading();
WebSettings ws = wv.getSettings();
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
wv.loadUrl(helpurl);
Toast.makeText(getApplicationContext(), "Page unavailable", Toast.LENGTH_SHORT).show();
}
else
{
wv.loadUrl(helpurl);
Toast.makeText(getApplicationContext(), "Page not cached", Toast.LENGTH_SHORT).show();
}
roe();
}
}
//checking connectivity by checking if site is reachable
public static boolean reachable(Context context)
{
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
try
{
URL url = new URL(mycaturl);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(5000); // five seconds timeout in milliseconds
urlc.connect();
if (urlc.getResponseCode() == 200) // good response
{ return true; } else { return false; }
}
catch (IOException e)
{ return false; }
}
else
{ return false; }
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onBackPressed ()
{
if (wv.isFocused() && wv.canGoBack())
{ wv.goBack(); } else { finish(); }
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.item1:
wv.loadUrl( helpurl );
break;
case R.id.item2:
wv.loadUrl( fbackurl );
break;
case R.id.item3:
String currurl=wv.getUrl();
wv.loadUrl(currurl);
break;
case R.id.item4:
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
break;
case R.id.item5:
finish();
break;
default:
break;
}
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
wv.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
wv.restoreState(savedInstanceState);
}
}
Should I also include manifest? Thanks in advance.
Put this in your web Activity :
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Then set :
your_webview.setWebViewClient(new MyWebViewClient());
Hope this will help you
Without the necessary code I have to assume this is what you need to add to your implementation.
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webview.loadUrl(url);
return true;
}
I am making my first Android app and I am trying to implement Leadbolt unlocker, I have done everything like Leadbolt documentation, but when I launch app it is always crashing. When I remove implement AdListener from public class FullActivity extends Activity implements AdListener then everything is working. App is crashing when Intent full = new Intent(GridActivity.this, FullActivity.class); and it is not even go to super.onCreate(savedInstanceState); breakpoint.
This is FullActivity.java:
import java.io.IOException;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.Leadbolt.AdController;
import com.Leadbolt.AdListener;
public class FullActivity extends Activity implements AdListener{
private AdController myController;
private String MY_LB_SECTION_ID="1111111";
private Integer[] mThumbIds = {
R.drawable.p1,
R.drawable.p2,
R.drawable.p3,
R.drawable.p4,
R.drawable.p5,
R.drawable.p6,
R.drawable.p7,
R.drawable.p8,
R.drawable.p9,
R.drawable.p10,
R.drawable.p11,
R.drawable.p12,
R.drawable.p13,
R.drawable.p14,
R.drawable.p15,
R.drawable.p16,
R.drawable.p17,
R.drawable.p18,
R.drawable.p19,
R.drawable.p20,
R.drawable.p21,
R.drawable.p22,
R.drawable.p23,
R.drawable.p24,
R.drawable.p25,
R.drawable.p26,
R.drawable.p27,
R.drawable.p28,
R.drawable.p29,
R.drawable.p30,
R.drawable.p31,
R.drawable.p32,
R.drawable.p33,
R.drawable.p34,
R.drawable.p35,
R.drawable.p36,
R.drawable.p37,
R.drawable.p38,
R.drawable.p39,
R.drawable.p40,
R.drawable.p41,
R.drawable.p42,
R.drawable.p43,
R.drawable.p44,
R.drawable.p45,
R.drawable.p46,
R.drawable.p47,
R.drawable.p48,
R.drawable.p49,
R.drawable.p50
};
Integer imageId;
TouchImageView touch;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
final Activity act = FullActivity.this;
final AdListener listener = FullActivity.this;
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
imageId = extras.getInt("image");
touch = new TouchImageView(this);
Bitmap snoop = BitmapFactory.decodeResource(getResources(), mThumbIds[imageId]);
touch.setImageBitmap(snoop);
touch.setMaxZoom(4f); //change the max level of zoom, default is 3f
setContentView(touch);
}
final String PREFS_NAME = "AppPrefs";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int ad = settings.getInt("ad", 0);
if((imageId > 25)&&(ad < 1)){
touch.post(new Runnable() {
public void run(){
myController = new AdController(act, MY_LB_SECTION_ID,
listener);
myController.loadAd();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.set_back:
setBack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setBack() {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(mThumbIds[imageId]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(FullActivity.this.getApplicationContext(), "Wallapers set!", Toast.LENGTH_SHORT).show();
}
public void onDestroy(){
myController.destroyAd();
super.onDestroy();
}
public void onAdClicked() {}
public void onAdClosed() {}
public void onAdCompleted() {
// TODO Auto-generated method stub
SharedPreferences settings = getSharedPreferences("AppPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("ad", 1);
// Commit the edits!
editor.commit();
}
public void onAdFailed() {
this.runOnUiThread(new Runnable() {
public void run() {
if(myController != null){
myController.destroyAd();
}
}
});
}
public void onAdLoaded() {}
public void onAdProgress() {}
}
We have made some adjustments to the code which should resolve this for you.
package com.mkstudio.hdwallpapers;
import java.io.IOException;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.Leadbolt.AdController;
import com.Leadbolt.AdListener;
public class FullActivity extends Activity{
private AdController myController;
private String MY_LB_SECTION_ID="729926945";
// references to our images
private Integer[] mThumbIds = {
R.drawable.p1,
R.drawable.p2,
R.drawable.p3,
R.drawable.p4,
R.drawable.p5,
R.drawable.p6,
R.drawable.p7,
R.drawable.p8,
R.drawable.p9,
R.drawable.p10,
R.drawable.p11,
R.drawable.p12,
R.drawable.p13,
R.drawable.p14,
R.drawable.p15,
R.drawable.p16,
R.drawable.p17,
R.drawable.p18,
R.drawable.p19,
R.drawable.p20,
R.drawable.p21,
R.drawable.p22,
R.drawable.p23,
R.drawable.p24,
R.drawable.p25,
R.drawable.p26,
R.drawable.p27,
R.drawable.p28,
R.drawable.p29,
R.drawable.p30,
R.drawable.p31,
R.drawable.p32,
R.drawable.p33,
R.drawable.p34,
R.drawable.p35,
R.drawable.p36,
R.drawable.p37,
R.drawable.p38,
R.drawable.p39,
R.drawable.p40,
R.drawable.p41,
R.drawable.p42,
R.drawable.p43,
R.drawable.p44,
R.drawable.p45,
R.drawable.p46,
R.drawable.p47,
R.drawable.p48,
R.drawable.p49,
R.drawable.p50
};
Integer imageId;
TouchImageView touch;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.full);
Bundle extras = getIntent().getExtras();
if (extras != null) {
imageId = extras.getInt("image");
touch = new TouchImageView(this);
Bitmap snoop = BitmapFactory.decodeResource(getResources(), mThumbIds[imageId]);
touch.setImageBitmap(snoop);
touch.setMaxZoom(4f); //change the max level of zoom, default is 3f
setContentView(touch);
}
final String PREFS_NAME = "SexyRec";
final Activity act = this;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int ad = settings.getInt("ad", 0);
if((imageId > 25)&&(ad < 1)){
touch.post(new Runnable() {
public void run(){
myController = new AdController(act, MY_LB_SECTION_ID, new AdListener() {
public void onAdProgress() {
// TODO Auto-generated method stub
}
public void onAdLoaded() {
// TODO Auto-generated method stub
}
public void onAdFailed() {
// TODO Auto-generated method stub
}
public void onAdCompleted() {
// TODO Auto-generated method stub
SharedPreferences settings = getSharedPreferences("SexyRec", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("ad", 1);
// Commit the edits!
editor.commit();
}
public void onAdClosed() {
// TODO Auto-generated method stub
}
public void onAdClicked() {
// TODO Auto-generated method stub
}
});
myController.loadAd();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.set_back:
setBack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setBack() {
//chuckNorris.setResourceAsWallpaper(mThumbIds[imageId]);
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(mThumbIds[imageId]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(FullActivity.this.getApplicationContext(), "Wallapers set!", Toast.LENGTH_SHORT).show();
}
public void onDestroy(){
myController.destroyAd();
super.onDestroy();
}
}