if there is no internet means I'm not able to load web resources. For this reason I'm giving the toast like "Check internet connectivity". After this toast, user may enable the internet option at notification bar and comes back. When he comes back, i want to reload the activity. For this requirement, i tried
onWindowFocusChanged and onActivityReenter
override methods but these are not working properly
MyCode
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
Intent intent = new Intent(CommonActivity.this, OtherActivity.class);
startActivity(intent);
}
}
When I'm using above code, my activity reloading again and again
There is a solution which i know is not perfect but it will work.
Define a activity level veriable like this
Boolean isAlreadyFocused = false;
Then in your onFocusChanged method do like this.
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus && !isAlreadyFocused ){
isAlreadyFocused = true;
Intent intent = new Intent(CommonActivity.this,OtherActivity.class);
startActivity(intent);
}else{
isAlreadyFocused = false;
}
}
Check this and tell me if this does not work.
By fallowing another way (i got this idea when i saw the flipkart app) i solved this internet checking
I'm checking for the internet connection, if there is no internet means i'm redirecting to NoInternetActivity that's design looks like
When user clicks on Retry button means i'm again checking for internet. If internet was accessible means i'm allowing user to home page of my app otherwise i'm redirecting to the NoInternetActivity again
Related
I am aware about the changes introduced in Android 6.0/SDKVersion 23 regarding the run-time permission. There is already discussion and talks on this topic in the below post which talks about the various aspects of new permission model.
"How to request permissions from a Service in Android Marshmallow"
Google I/O 2015 - Android M Permissions
"Mother, May I?" Asking for Permissions (Android Dev Summit 2015)
After going thorough these article,I believe below is suggested to "workaround" (as Service doesnot have UI support)this problem.
Check permission checkSelfPermission() in the context of
Service.
Notify it to status bar in case the permission is denied.
User would now click on status bar which would launch a new
DialogActivity to request for permission when users press on the
notification.
I am not able to make the workable version of the suggestions provided to achieve this task. When we launch DialogActivity to ask for permission, it would be assigned and available for that activity. It would not be applicable for background service who had put it on status bar and even after this service would not be granted this permission(instead the permission would be given to DialogActivity).
Could somebody provide the input(possibly workable logic/code) so that I can make it workable(.i.e. execute the code in the context of Service which would be dependent on whether permission is granted or not).
My Scenario
Develop application which would send the SMS at regular interval
regarding the my current location.
I have designed the UI for this application as mentioned below. It had some settings parameters and also buttons which would start the main logic which is:
Start monitoring the current location and
Send the SMS to configured contact numbers.
I believe user would minimize this application( as it does not have any interesting logic apart from sending the SMS) and it should continue to work in background(.i.e. monitoring the location and sending the SMS). Hence I thought to use move this logic in Service instead of keeping it the Activity itself. If I keep these logic in Activity itself, it works as expected however for that user is suppose to keep the application in foreground all the time.
So far I have been able to achieve the following:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Define START/STOP button handles.
mStartApp = (ImageButton)findViewById(R.id.startApp);
mStopApp = (ImageButton)findViewById(R.id.stopApp);
//Write event handlers for above grabbed buttons.
mStartApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent startService = new Intent(getApplicationContext(),
CurrentLocationTrackerService.class);
startService(startService);
}
});
mStopApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent stopService = new Intent(getApplicationContext(),
CurrentLocationTrackerService.class);
stopService(stopService);
}
});
// Support for the ActionBar widgets menu in current activity.
Toolbar mToolBar = (Toolbar)findViewById(R.id.myToolbar);
if(mToolBar != null) {
setSupportActionBar(mToolBar);
}
}
//Other methods.....
}
public class CurrentLocationTrackerService extends Service {
public CurrentLocationTrackerService() { }
#Override
public void onCreate() { }
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int permissionLocationAccess = ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.ACCESS_FINE_LOCATION);
// If permissionLocationAccess is true execute further
// If permissionLocationAccess false(which would always as we are in Service and it is dangerous
// permission) we need to put some information to status bar. Post that user would click on that
// which would launch some new activity where UI of asking permission would be shown. But still
// Service would not get the permission( only new activity would have that permission but it is
// of no use here as I am planning to put these logic iside the Service as my app may not be always
// be in foreground)
}
}
Hope I have provided all detail regarding the problem and also my application context regarding why I require to model in this way.The real point over here is how to achieve this.
I am really stuck at this point and any help would be highly appreciated. Kindly let me know in case anything else is required from my side.
I tried this example & it is working fine.
But I don't want to see print popup.
Is it possible to prevent the print popup?
Since PrintManager is final you can't override it's methods
But you can hide all System Dialogs using this
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (! hasFocus) {
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
and If you want an example for Printing document you can refer to Android-wifi-print - GitHub. This is just a prototype for printing document with the help of wifi printer.
I currently developing a Content Management app in Kiosk Mode. I pattern this in Surelock Kiosk Lockdown. There's an admin password in order to allow application to run inside the app. The buttons like Home, Back and Recent Task App are disabled in this app. However when I launch a certain app, Back button and Recent Task App are enabled again.
What I'd like to happen is that when the user launch an app, the Recent Task app button and Back button are disabled just like in Content Management App. I am stuck in searching and finding ways on how to do this. Please help me on how to do this. Thank you.
BTW, I'm using this code to disable Buttons:
// Disable Recent Task App
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d("Focus debug", "Focus changed!");
if (!hasFocus) {
Log.d("Focus debug", "Lost focus!");
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
closeDialog.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
sendBroadcast(closeDialog);
}
}
// Disable Volume Buttons and Back Button
private final List hijackKeys = new ArrayList(Arrays.asList(
KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_UP,
KeyEvent.KEYCODE_BACK));
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (hijackKeys.contains(event.getKeyCode())) {
return true;
} else {
return super.dispatchKeyEvent(event);
}
}
We have to show a license agreement dialog when user use the application at the first time, now I have two questions about this:
1 Where to put this dialog?
Add another activity or put the dialog just at the MainActivity which is the launch acitivty?
2 How to close the app if user hit "Reject"
Once user hit the "Reject" button which means that he/she does not agree our license, then we have to exit the application completely. How to make it?
According to the answer of "Ahmad", I will decide to open a dialog or not at the beginning of the activity(the onCreate method):
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
this.setupLicense();
this.setupViews();
this.initSomeJob();
}
private void setupLicense() {
SharedPreferences setting = getSharedPreferences(IConstant.Map_License, 0);
boolean mapLicenseAccept = setting.getBoolean(IConstant.Map_License, false);
if (!mapLicenseAccept) {
//user does not accept the license yet, we will open the dialog
showDialog(Dialog_Map_License);
}
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
switch (id) {
case Dialog_Map_License:
builder.setIconAttribute(android.R.attr.alertDialogIcon)
.setTitle(R.string.map_license_title)
.setMessage(R.string.map_license_content)
.setPositiveButton(R.string.map_license_accept, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//License accepted, persisted it.
SharedPreferences settings = getSharedPreferences(IConstant.Map_License, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(IConstant.Map_License, true);
editor.commit();
}
})
.setNegativeButton(R.string.map_license_reject, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//do nothing and exit
Process.killProcess(Process.myPid());
System.exit(0);
}
});
Dialog target = builder.create();
target.setCanceledOnTouchOutside(false);
return target;
}
return null;
}
But now I have meet two problem:
1 Event I choose the "Accept" button, once I open my app the second time, the dialog will show.
It seems that the following code does not work:
editor.putBoolean(IConstant.Map_License, true);
editor.commit();
2 When I show the dialog, the code:
this.setupViews();
this.initSomeJob();
will still run , they are not blocked which is out of expected, since nothing should be done before user hit the "Accept" button.
Any idea to fix it?
onCreateDialog has been deprecated. Use dialog fragment instead. The advantage will be that the code for displaying dialog will be moved from activity and you can then display dialog from any activity. Also move
SharedPreferences setting = getSharedPreferences(IConstant.Map_License, 0);
boolean mapLicenseAccept = setting.getBoolean(IConstant.Map_License, false);
to a utility method like isLicenceAccepted and similarly for storing the data
SharedPreferences settings = getSharedPreferences(IConstant.Map_License, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(IConstant.Map_License, true);
editor.commit();
to method like acceptLicence in utility.
You can find how to make communication between dialog Fragment and your activity here. In your interface instead of onArticleSelected you will have to implement two methods onLicence accepted and onLicenceRejected. Implement the interface in you activity override these two methods and take appropriate action.
Where to put this dialog?
Right at the beginning, when the user opens the app for the first time. Keep track of that by saving it in your shared preferences, if this dialog has been already shown or not. You don't have to create a separate activity for this. You could, but most apps I've seen out there don't.
How to close the app if user hit "Reject"
Just finish the Activity and also save that in your shared preferences as well. So every time the user opens your app you check weather the boolean value for "hasUserAcceptedOurAgreement" is true or not and proceed depending on that.
I'm only answering from a technical standpoint on how this could be done reliably. I'm not a lawyer, but as far as I know, it's perfectly valid to just submit your license agreement to the play store, so it's available from the applications application page (Why else would there be this option?).
We suppose that a url is already loaded (Let's call it the original url).
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("file:///android_asset/missing.html");
}
});
I have created my own error page to prevent the "web page not available message" to appear.
The app must reload the webview every time it is resumed. So i have the following lines of code:
#Override
protected void onResume() {
super.onResume();
webView.reload();
}
The problem here is that when the error page is loaded (for example when the user is not connected to the internet), and then a connection is available again and the user resumes the app, the original url is not loaded (which seems logic, the current now is missing.html). But is this a nice approach? Any suggestions for the problem?
There is also a refresh button if the user wants to reload the content. Same issue here.
You should load the wanted url instead of using webView.reload(), like this:
webView.loadUrl("http://yoururl");
or go back to previous page with:
webView.loadUrl("javascript:history.go(-1)");
I'd examine internet connectivity in onResume() like suggested on http://developer.android.com/training/basics/network-ops/managing.html
public static boolean isOnline() {
ConnectivityManager connMgr = (ConnectivityManager) App.instans.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
public void onResume() {
It's not just the mobile connection that can drop but also the page can become unavailable and as you rightly say using webview.loadUrl("someerrorpage.html") will create fake history and cause problems if the user tries to refresh or press back.
My solution was to replace the contents of the default error page with my own custom one e.g.
webView.evaluateJavascript("javascript:document.open();document.write('your custom error html');document.close();", null);