When going back through activities, application stalls - android

I have this code, that goes through steps, aquired from a webservice.
I implemented my own history, so that the user can go back through performed steps.
The problem is that the same step can be visited more than once and that seems to cause my history to fail.
It can go back just fine, but sometimes it takes more than one press on the back button to go to the previous step.
Here's the code for my class that manages history:
private ArrayList<String> idList;
#Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
if ( idList == null )
{
idList = new ArrayList<String>();
}
}
#Override
public void finishFromChild( Activity child )
{
LocalActivityManager manager = getLocalActivityManager();
int index = idList.size()-1;
if ( index < 1 )
{
finish();
return;
}
manager.destroyActivity( idList.get( index ), true );
idList.remove( index ); index--;
String lastId = idList.get( index );
Activity lastActivity = manager.getActivity( lastId );
Intent lastIntent = lastActivity.getIntent();
Window newWindow = manager.startActivity( lastId, lastIntent );
setContentView( newWindow.getDecorView() );
}
public void startChildActivity( String id, Intent intent )
{
id += System.currentTimeMillis();
if ( "restart".equalsIgnoreCase( id ) )
{
idList.clear();
}
Window window = getLocalActivityManager().startActivity( id, intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP ) );
if ( window != null )
{
idList.add( id );
setContentView( window.getDecorView() );
}
}
public Activity getCurrentActivity()
{
int length = idList.size();
if ( idList.isEmpty() ) {
return null;
}
else
{
return getLocalActivityManager().getActivity( idList.get( length-1 ) );
}
}
#Override
public boolean onKeyDown( int keyCode, KeyEvent event )
{
if ( keyCode == KeyEvent.KEYCODE_BACK )
{
return true;
}
return super.onKeyDown( keyCode, event );
}
#Override
public boolean onKeyUp( int keyCode, KeyEvent event )
{
if ( keyCode == KeyEvent.KEYCODE_BACK )
{
onBackPressed();
return true;
}
return super.onKeyUp( keyCode, event );
}
#Override
public void onBackPressed()
{
int length = idList.size();
if ( length > 1 )
{
Activity current = getLocalActivityManager().getActivity( idList.get( length-1 ) );
current.finish();
}
}

Turns of that the FLAG_ACTIVITY_CLEAR_TOP flag
in my method
public void startChildActivity( String id, Intent intent )
{
id += System.currentTimeMillis();
if ( "restart".equalsIgnoreCase( id ) )
{
idList.clear();
}
Window window = getLocalActivityManager().startActivity( id, intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP ) );
if ( window != null )
{
idList.add( id );
setContentView( window.getDecorView() );
}
}
Was messing things up, now everything is working perfectly.

Related

onbackpress app got crash

I have three activites A,B and C,now what i am doing is,From Activity A i am sending one data to B
Activity B
Intent intent=getIntent();
userids= intent.getStringExtra("userid");
System.out.println("USERID BC"+userids);
pname = intent.getStringExtra("names");
occasions = intent.getStringExtra("oca");
System.out.println("OC BC"+occasions);
pics = intent.getStringExtra("photo");
dates = intent.getStringExtra("datess");
realtions = intent.getStringExtra("realations");
friendid = intent.getStringExtra("friendid");
System.out.println("Frnd BC"+friendid+userids);
sendgift=(ImageView)findViewById(R.id.wishfriend_sendgift);
ImageView propic=(ImageView)findViewById(R.id.wishfriend_propic);
username=(TextView)findViewById(R.id.wishfriend_name);
ocasions=(TextView)findViewById(R.id.wishfriend_occasion);
datess=(TextView)findViewById(R.id.wishfriend_dates);
pointshori=(HorizontalScrollView)findViewById(R.id.pointshori);
yourLayout = (LinearLayout)findViewById(R.id.linearhori);
selectedpoints=(TextView)findViewById(R.id.wishfrindselectdpoints);
username.setText(pname);
ocasions.setText(occasions);
datess.setText("Date: " + dates);
aQuery.id(propic).image(pics, true, true, 0, R.drawable.male);
PLACE_URL = "http:///webservices/wish_friend.php?user_id="+userids+"&det="+friendid+"&occ="+ URLEncoder.encode(realtions);
WISHU_URL = "http:///webservices/wish_friend.php?user_id="+userids;
sendgift.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtmessages.getText().toString().trim().equals(""))
{
Toast.makeText(getApplicationContext(),"Enter Message",Toast.LENGTH_SHORT).show();
}
else if(giftpointss.toString().equals("0"))
{
Toast.makeText(getApplicationContext(),"Sorry you can not gift with 0 points",Toast.LENGTH_SHORT).show();
}
else
{
new AttemptLogin().execute();
}
}
});
new LoadAllPreset().execute();
new LoadPlacestatus().execute();
that is working fine,now i am going to B to C,but when i come back from C to B my app got crash,,getting null pointer exception
here
PLACE_URL = "http:///webservices/wish_friend.php?user_id="+userids+"&det="+friendid+"&occ="+ URLEncoder.encode(realtions);
Just check before accessing intent data
if( getIntent().getExtras() != null){
// intent has data
Intent intent=getIntent();
userids= intent.getStringExtra("userid");
...
}
else
{
//probably you are from C->B after back press
}

How to handle double click from headset hook?

I would like to control my squash score counter app via only one head set button. It means that I want to detect single or double click and add score to first or second player according to number of clicks.
I cannot use long click, instead of double click, because long click activate Google Now.
This is what I used in my music player to handle headset control single and double click.
static final long CLICK_DELAY = 500;
static long lastClick = 0; // oldValue
static long currentClick = System.currentTimeMillis();
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_MEDIA_BUTTON)) {
KeyEvent keyEvent = (KeyEvent) intent.getExtras().get(Intent.EXTRA_KEY_EVENT);
if (keyEvent.getAction() != KeyEvent.ACTION_DOWN)return;
lastClick = currentClick ;
currentClick = System.currentTimeMillis();
if(currentClick - lastClick < CLICK_DELAY ){
//This is double click
} else {
//This is single click
}
}
Too late, but maybe someone else will find it useful, with triple clicks like Google Music, Spotify, etc.
const val DOUBLE_CLICK_TIMEOUT = 430L
private var mHeadsetHookClickCounter = 0
override fun onMediaButtonEvent(mediaButtonEvent: Intent?): Boolean {
if (Intent.ACTION_MEDIA_BUTTON == mediaButtonEvent?.action) {
val ke = mediaButtonEvent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT)
if (ke != null && ke.keyCode == KeyEvent.KEYCODE_HEADSETHOOK) {
if (ke.action == KeyEvent.ACTION_UP) {
mHeadsetHookClickCounter = min(mHeadsetHookClickCounter+1, 3)
if (mHeadsetHookClickCounter == 3) {
handlingHeadsetClick()
} else {
Handler().postDelayed({
handlingHeadsetClick()
}, DOUBLE_CLICK_TIMEOUT)
}
}
return true
}
}
return super.onMediaButtonEvent(mediaButtonEvent)
}
private fun handlingHeadsetClick() {
logd("MediaSessionSupportFeature Handling headset click")
when(mHeadsetHookClickCounter) {
1 -> { service.get()?.togglePlayPause() }
2 -> { service.get()?.playNext() }
3 -> { service.get()?.playPrevious() }
}
// Reset Counter
mHeadsetHookClickCounter = 0
return
}

Android service sleep when screen is off

In my application service I'm fetch server to get new message.
After found new message my serivce application must be screen on and start activity to display a new message.
In service I don't have problem to resolve data from server, but when screen is off that cause of sleeping service and after start activity, that could not screen on.
activity start by service:
public void onCreate (Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
requestWindowFeature ( Window.FEATURE_NO_TITLE );
getWindow ().setFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN );
PowerManager powermanager = ((PowerManager)getBaseContext ().getSystemService( Context.POWER_SERVICE));
wakeLock=powermanager.newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP, "TsmsScreenOn");
wakeLock.acquire ( 10000 );
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 1.0f;
getWindow().setAttributes(params);
setContentView ( R.layout.service_view_dialog );
}
My summarized service:
public class ToobaPayamakService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
}
private Runnable sendUpdatesToUI = new Runnable() {
};
private void DisplayLoggingInfo() {
}
public int callRequestFromServer(){
if (G.checkInternetConnection ()) {
try {
Cursor c = db.getCursorFirstItemReceived ( username );
c.moveToFirst ();
if (c.moveToFirst ()) {
receive_lastID = c.getString ( c.getColumnIndex ( "lastId" ) );
}
c.close ();
unread = checkWebService ( Integer.valueOf ( receive_lastID ) );
} catch (Exception e) {
e.printStackTrace ();
}
Log.e ( "unread: ", unread + "" );
if (unread != 0) {
G.config_username = username;
G.config_password = password;
try {
G.getRequestFromServerByService ( Long.parseLong ( receive_lastID ), unread, contentResolver );
result_count = unread;
} catch (JSONException e) {
e.printStackTrace ();
}
}
}
return result_count;
}
/* ----------------------------------------------------------------------------------------------------------------- notifyTest */
public void notifyTest ( int unread ) {
Intent i = new Intent ();
i.setClass ( this, ServiceDialog.class );
i.putExtra ( "username", username );
i.putExtra ( "password", password );
i.putExtra ( "unread" , counter );
i.putExtra ( "notify" , notify );
i.setFlags ( Intent.FLAG_ACTIVITY_REORDER_TO_FRONT );
i.setFlags ( Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity ( i );
}
}
The answer is simple: you have to grab a wakelock in your service.
You can also use this flag to keep your screen ON -
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
One more solution using Wakelock -
private PowerManager.WakeLock wl;
Inside onCreate -
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "doneDimScreen");
Inside onPause -
wl.release();
Inside onResume -
wl.acquire();
you have to add this permission as well for the Wakelock to work -
<uses-permission android:name="android.permission.WAKE_LOCK" />
For more detail on Wakelock refer - this
Cheers :)

ProgressBar and AsyncTask

I currently have an AsyncTask running that updates the progress bar inside the Activity while downloading a file. The problem is when i leave the Activity and reenters, the ProgressBar will not update anymore.
I tried running the AsyncTask inside a Service but i have no idea how to send the ProgressBar value back to my Activity's UI thread.
I came to the same problem as you did:
I wanted an async task executed (as service)
I wanted to be able to rotate the device, be able to update the UI even if the task finished while the screen was off and I got no notification.
I came up with something like:
public class DatabaseIncompleteActivity extends RoboActivity {
private BroadcastReceiver receiver;
private ProgressDialog progressDialog;
#Inject
private DatabaseSetManager databaseSetManager;
#Inject
private DatabaseDownloadLogger databaseDownloadLogger;
private LocalBroadcastManager localBroadcastManager;
private String jobId;
private static final int ERROR_RETRY_DIALOG = 1;
private static final String ERROR_MESSAGE = "errorMsg";
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
localBroadcastManager = LocalBroadcastManager.getInstance( this );
showProgressDialog();
if ( getLastNonConfigurationInstance() == null ) {
startService();
}
}
private void showProgressDialog() {
progressDialog = new ProgressDialog( this );
progressDialog.setMessage( getString( R.string.please_wait ) );
progressDialog.setProgressStyle( ProgressDialog.STYLE_HORIZONTAL );
progressDialog.setIndeterminate( true );
progressDialog.setCancelable( false );
progressDialog.show();
}
private void startService() {
this.jobId = UUID.randomUUID().toString();
Intent intent = new Intent( this, ClientDatabaseDroidService.class );
intent.putExtra( ClientDatabaseDroidService.JOB_ID,
jobId );
intent.putExtra( ClientDatabaseDroidService.INTERACTIVE,
true );
startService( intent );
}
private void registerListenerReceiver() {
if ( receiver != null ) {
return;
}
localBroadcastManager.registerReceiver( this.receiver = new ClientDatabaseBroadcastReceiver(),
new IntentFilter( ClientDatabaseDroidService.PROGRESS_NOTIFICATION ) );
}
#Override
protected void onPause() {
super.onPause();
unregisterListenerReceiver();
}
#Override
protected void onResume() {
super.onResume();
DatabaseDownloadLogEntry logEntry = databaseDownloadLogger.findByJobId( jobId );
// check if service finished while we were not listening
if ( logEntry != null ) {
if ( logEntry.isSuccess() )
onFinish();
else {
Bundle bundle = new Bundle();
bundle.putString( ERROR_MESSAGE,
logEntry.getErrorMessage() );
onError( bundle );
}
return;
}
registerListenerReceiver();
}
#Override
public Object onRetainNonConfigurationInstance() {
return Boolean.TRUE;
}
final class ClientDatabaseBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive( Context context, Intent intent ) {
Bundle extras = intent.getExtras();
int eventType = extras.getInt( ClientDatabaseDroidService.EVENT_TYPE );
switch ( eventType ) {
case ClientDatabaseDroidService.EVENT_TYPE_DOWNLOADING:
onDownloading( extras );
break;
case ClientDatabaseDroidService.EVENT_TYPE_FINISHED:
onFinish();
break;
case ClientDatabaseDroidService.EVENT_TYPE_ERROR:
Bundle bundle = new Bundle();
bundle.putString( ERROR_MESSAGE,
extras.getString( ClientDatabaseDroidService.EXTRA_ERROR_MESSAGE ) );
onError( bundle );
break;
default:
throw new RuntimeException( "should not happen" );
}
}
}
private void unregisterListenerReceiver() {
if ( receiver != null ) {
localBroadcastManager.unregisterReceiver( receiver );
receiver = null;
}
}
private void onError( Bundle extras ) {
progressDialog.dismiss();
showDialog( ERROR_RETRY_DIALOG,
extras );
}
private void onFinish() {
progressDialog.dismiss();
setResult( RESULT_OK );
finish();
}
#Override
protected Dialog onCreateDialog( final int id, Bundle args ) {
if ( id == ERROR_RETRY_DIALOG ) {
Builder builder = new AlertDialog.Builder( this );
builder.setTitle( R.string.error );
builder.setMessage( "" );
builder.setPositiveButton( R.string.yes,
new OnClickListener() {
#Override
public void onClick( DialogInterface dialog, int which ) {
showProgressDialog();
startService();
}
} );
builder.setNegativeButton( R.string.no,
new OnClickListener() {
#Override
public void onClick( DialogInterface dialog, int which ) {
setResult( RESULT_CANCELED );
finish();
}
} );
return builder.create();
}
return super.onCreateDialog( id,
args );
}
#Override
protected void onPrepareDialog( int id, Dialog dialog, Bundle args ) {
if ( id == ERROR_RETRY_DIALOG ) {
( (AlertDialog) dialog ).setMessage( String.format( "%s\n\n%s",
args.getString( ERROR_MESSAGE ),
getString( R.string.do_you_wish_to_retry ) ) );
return;
}
super.onPrepareDialog( id,
dialog );
}
private void onDownloading( Bundle extras ) {
String currentDatabase = extras.getString( ClientDatabaseDroidService.EXTRA_CURRENT_CLASSIFIER );
Progress databaseProgress = extras.getParcelable( ClientDatabaseDroidService.EXTRA_DATABASE_PROGRESS );
Progress downloadProgress = extras.getParcelable( ClientDatabaseDroidService.EXTRA_DOWNLOAD_PROGRESS );
progressDialog.setIndeterminate( false );
progressDialog.setMessage( String.format( "[%d/%d] %s",
databaseProgress.getProcessed(),
databaseProgress.getSize(),
currentDatabase ) );
progressDialog.setProgress( (int) downloadProgress.getProcessed() );
progressDialog.setMax( (int) downloadProgress.getSize() );
}
}
The main idea is:
The activity communicates with service via broadcast. The following events are dispatched from service to UI: download progress (reported each x bytes), download finished, error occured
Each activity start is being assigned a unique job ID which is kept for screen rotation.
Each job result is being persisted into database (or any other persistent storage). This way I can get the job result even if broadcast received was not listening at the moment (screen was off).
hope that helps.
Make in your activity static progress variable
Save progress to preferences
When you re-enter activity grab and set progress from static variable or preferences.
This is normal. Activities die when you leave them or rotate your device. Then they are recreated. AsyncTasks don't relink to the new Activity instance automatically.
Actually, RoboSpice is the library you are looking for : it will allow you to launch a download from an activity, rotate the device, leave the activity, even leave the app, even kill it using the task switcher and your download will survive. Any activity, a new instance of your former activity, or even a completely different one will be able to relink to your download.
You should download the app RoboSpice Motivations from the store, it will explain you why it's not a good idea to use AsyncTasks for networking and show you how to use RoboSpice.
To get a good & fast overview of this problem, please have a look at this infographics.
Also note that if you only download binary data and are not interested in POJOs for instance, then you can use RoboSpice still or the DownloadManager (but it's API is less intuitive than RoboSpice).

Check for internet connection

I guess I should start off by saying that I'm completely new to eclipse and java. I'm trying to create a android app using eclipse that launches my web page. I have an example of my code that works just fine, but it's pretty much copied and pasted from examples that I've found online so please excuse my sloppy code. I would like to know how to check if an internet or wifi connection is available.. If there is no connection show an alert (No Internet Connection).. I found some similar questions but, I'm just not sure where to place the code? Can someone please show me?
package com.mysite.news;
import com.mysite.news.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class WebActivity extends Activity {
private WebView wv;
private String LASTURL = "";
Menu myMenu = null;
private static final String PREFS_NAME = "MyPrefs";
private Boolean imgOn;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
this.getWindow().requestFeature( Window.FEATURE_PROGRESS );
setContentView( R.layout.web_view );
wv = ( WebView ) findViewById( R.id.web_view );
WebSettings webSettings = wv.getSettings();
webSettings.setSavePassword( true );
webSettings.setSaveFormData( true );
webSettings.setJavaScriptEnabled( true );
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSupportZoom(false);
SharedPreferences settings = getSharedPreferences( PREFS_NAME, 0 );
imgOn = settings.getBoolean( "IMGMODE", false );
webSettings.setLoadsImagesAutomatically( imgOn );
final Activity activity = this;
// start ProgressDialog with "Page loading..."
final ProgressDialog dialog = new ProgressDialog( activity );
dialog.setMessage( "Page loading..." );
dialog.setIndeterminate( true );
dialog.setCancelable( true );
dialog.show();
wv.setWebChromeClient( new WebChromeClient() {
public void onProgressChanged( WebView view, int progress ) {
// set address bar and progress
// activity.setTitle( " " + LASTURL );
// activity.setProgress( progress * 100 );
if( progress == 100 ) {
// stop ProgressDialog after loading
dialog.dismiss();
// activity.setTitle( " " + LASTURL );
}
}
} );
wv.setWebViewClient( new WebViewClient() {
public void onReceivedError( WebView view, int errorCode, String description, String failingUrl ) {
Toast.makeText( getApplicationContext(), "Error: " + description + " " + failingUrl, Toast.LENGTH_LONG ).show();
}
#Override
public boolean shouldOverrideUrlLoading( WebView view, String url ) {
if( url.indexOf( "mysite" ) <= 0 ) {
// the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( url ) );
startActivity( intent );
return true;
}
return false;
}
public void onPageStarted( WebView view, String url, Bitmap favicon ) {
LASTURL = url;
view.getSettings().setLoadsImagesAutomatically( true );
view.getSettings().setBuiltInZoomControls( true );
}
public void onPageFinished( WebView view, String url ) {
view.loadUrl( "javascript:(function() { " +
"hide('sidebar');" +
//"var parent = document.getElementsByClassName('page-navigation')[0];"+
//"var panel = document.getElementsByClassName('panel-tools')[0];"+
//"var div = document.createElement('div');"+
//"div.innerHTML = panel.innerHTML;"+
//"parent.appendChild(div);"+
//"panel.innerHTML = '';"+
//"div.style['margin-left'] = '31px';"+
"var panel = document.getElementById('search');" +
"panel.style['width'] = '55px';" +
//"var imgs=document.getElementsByTagName('IMG');for(var i=0;i<imgs.length;i++){if (imgs[i].height=60) {imgs[i].src='';imgs[i].width=0;} }"+
//"var urls=document.getElementsByTagName('li');for(var i=0;i<urls.length;i++){if (urls[i].style='margin: -14px 0pt 0pt;'){urls[i].style['display'] = 'none';}}"+
//"hideByClass('panel-tools');"+
"function hide(id){if (document.getElementById(id)){document.getElementById(id).style['display'] = 'none';}}" +
//"function hideByClass(c){var e=document.getElementsByClassName(c);for(var i=0;i<e.length;i++){e[i].style['display'] = 'none';}}"+
"})()" );
if( imgOn ) {
view.getSettings().setLoadsImagesAutomatically( true );
view.getSettings().setSupportZoom(false);
}
}
} );
wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
wv.setScrollbarFadingEnabled(false);
wv.loadUrl( "http://www.mysite.com" );
}
#Override
public boolean onKeyDown( int keyCode, KeyEvent event ) {
if( ( keyCode == KeyEvent.KEYCODE_BACK ) && wv.canGoBack() ) {
wv.goBack();
return true;
}
return super.onKeyDown( keyCode, event );
}
#Override
public boolean onCreateOptionsMenu( Menu menu ) {
super.onCreateOptionsMenu( menu );
this.myMenu = menu;
MenuItem item = menu.add( 0, 1, 0, "MAIN PAGE" );
item.setIcon( R.drawable.home );
MenuItem item2 = menu.add( 0, 2, 0, "BACK" );
item2.setIcon( R.drawable.arrowleft );
MenuItem item3 = menu.add( 0, 3, 0, "Reload" );
item3.setIcon( R.drawable.s );
MenuItem item4 = menu.add( 0, 4, 0, "CLEAR CACHE" );
item4.setIcon( R.drawable.trash );
MenuItem item5 = menu.add( 0, 5, 0, "Rate" );
item5.setIcon( R.drawable.vote );
MenuItem item6 = menu.add( 0, 6, 0, "Exit" );
item6.setIcon( R.drawable.close );
return true;
}
#Override
public boolean onOptionsItemSelected( MenuItem item ) {
switch( item.getItemId() ) {
case 1:
wv.loadUrl( "http://mysite.com" );
break;
case 2:
if( wv.canGoBack() ) {
wv.goBack();
}
break;
case 3:
wv.loadUrl( LASTURL );
break;
case 4:
wv.clearCache( true );
break;
case 5:
Intent marketIntent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(
"https://play.google.com/store/apps/details?id=" + getPackageName()));
startActivity(marketIntent2);
break;
case 6:
finish();
break;
}
return true;
}
private void saveSettings( Boolean val ) {
SharedPreferences settings = getSharedPreferences( PREFS_NAME, 0 );
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean( "IMGMODE", val );
editor.commit();
}
}
private boolean checkNetwork() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
Toast.makeText(getApplicationContext(),
"Sorry, Network Unavailable! :(", Toast.LENGTH_LONG).show();
}
return false;
}
This snippet helped me out, hope it helps you too. Your usage might look like this.
if (!checkNetwork()) {
//TODO Network Not Available
} else {
//TODO Network Available
}
You might want to put the Toast notification NOT in the function().
check this link
How do you check the internet connection in android?
Use the same solution before you load the url. Show an error dialog if internet is not available else load the url
Here's a helper class I use for Network Connectivity:
public class NetworkUtils
{
public static boolean isOnline( Service service )
{
ConnectivityManager cm = (ConnectivityManager) service.getSystemService( Context.CONNECTIVITY_SERVICE );
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if ( netInfo != null && netInfo.isConnected() )
{
return true;
}
return false;
}
}
And don't forget to add the permissions to AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

Categories

Resources