Change screen orientation automatically while scanning (using ZXING library) - android

I've MainActivity.kt where I show different fragments for different needs. At some point, I press button 'X' that calls startScanner() function:
private fun startScanner() {
IntentIntegrator(this)
.setOrientationLocked(false)
.setPrompt("SCANNING?")
.initiateScan()
}
Manifest.xml:
<activity
android:name=".MainActiity"
android:theme="#style/AppTheme"
tools:replace="android:screenOrientation"
android:stateNotNeeded="true"
android:screenOrientation="fullSensor"
android:windowSoftInputMode="stateHidden" />
Gradle.file:
compile 'com.journeyapps:zxing-android-embedded:3.6.0'
It does open scanner and everything, but in landscape mode.
Why is this not working?

There is a shortcut to do this. Just add this to the manifest:
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="portrait"
tools:replace="android:screenOrientation"
android:stateNotNeeded="true"/>

in addition of this answer https://stackoverflow.com/a/35465968/7666442
I found way to change Orientation of zxing scanner activity automatically when device Orientation change
Try this way
CaptureActivityPortrait
public class CaptureActivityPortrait extends CaptureActivity {
//Nothing in side.
}
CaptureActivityPortrait in manifest file
<activity
android:name=".CaptureActivityPortrait"
android:stateNotNeeded="false"
android:theme="#style/zxing_CaptureTheme"
android:windowSoftInputMode="stateAlwaysHidden"/>
use this way in your activity
public class MyActivity extends AppCompatActivity {
IntentIntegrator qrScan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
qrScan = new IntentIntegrator(this).setCaptureActivity(CaptureActivityPortrait.class);
qrScan.setOrientationLocked(false);
qrScan.initiateScan();
}
}

You can set the orientation programmatically (in your activity):
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Related

Close android activity (completely, not even in background) using finish on a button click

I need to close an activity when a button is clicked. Unfortunately, when button is clicked, the activity does disappear but is still in the background. User can still select it and it comes back to front. What I need is the activity completely gone/destroyed.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
I searched on SO on related questions, however, none of them help with closing the activity completely. I already tried adding return, adding another broadcast listener and passing command to call finish outside onCreate. So at this point, the question is - is this really possible or is this how Android works, you can call finish() but it is still in the background and user can re-launch it.
Here is xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app1.test.myapplication">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
EDIT: Adding android:excludeFromRecents="true" does not solve the issue. Here are steps to recreate this, if anyone thinks it is a duplicate or already solved, please try and post comment/answer, I will accept it.
Open Android Studio
Create empty activity project.
Add a button.
Add code in MainActivity's onCreate for button click listener.
Inside click listener, call finish.
Run the app and click button and see if the activity is still in background or not.
Just give it a try.
In you manifest.
<activity
android:excludeFromRecents="true"
android:name=".Activities.SplashActivity"
android:theme="#style/AppThemeSubActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Now in your java code.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_search:
// Intent intent = new Intent(MainActivity.this, SearchActivity.class);
// startActivity(intent);
finish();
System.exit(0);}
}
put the extra line System.exit(0); after calling finish it works for me.
You need to put this in your XML manifest:android:excludeFromRecents="true"
in your Activity TAG.
<activity
...
android:excludeFromRecents="true">
</activity>
You could try this
android:excludeFromRecents="true", Use it in your manifest.
plz try this to go back
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
}
}
and this code to kill app process
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);

why the "up" button moves me to the main activity and not to the parent activity

I have an application with three activities.
MainActivity which looks like that:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button b = new Button(this);
b.setText("click me to go to child activity");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ChildActivity.class));
}
});
setContentView(b);
}
}
ChildActivity which looks like that:
public class ChildActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TextView(this) {{
setText("I'm the child activity");
}});
}
}
And OtherActivity which looks like that:
public class OtherActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TextView(this) {{
setText("I'm other activity");
}});
}
}
In the manifest I have such declaration:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:name="pl.psobolewski.test.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name="pl.psobolewski.test.ChildActivity" />
<activity android:name="pl.psobolewski.test.OtherActivity" />
</application>
Now when I start the application, it starts with MainActivity, from there I can go to ChildActivity, but there is no way to go to OtherActivity.
Then in the manifest I change this line:
<activity android:name="pl.psobolewski.test.ChildActivity" />
to:
<activity android:name="pl.psobolewski.test.ChildActivity" android:parentActivityName="pl.psobolewski.test.OtherActivity" />
Now I start again this application on my phone, which has Android API 16. It starts with MainActivity, there I can press the button and move to ChildActivity. Now the ChildActivity looks a little bit different than before: the logo on ActionBar has a little arrow-like icon (documentation calls it "a left-facing caret") which means it can be used to move up. But when I press it I don't go to OtherActivity - even though it is declared as the parent of ChildActivity - but to the MainActivity.
I find it contrary with the Android documentation which says:
http://developer.android.com/guide/topics/manifest/activity-element.html
"android:parentActivityName
The system reads this attribute to determine which activity should be started when the use presses the Up button in the action bar. The system can also use this information to synthesize a back stack of activities with TaskStackBuilder."
I also thought that adding android:parentActivityName attribute without calling setDisplayHomeAsUpEnabled would not turn the application logo into the up button - the documentation at http://developer.android.com/training/implementing-navigation/ancestral.html suggests so.
My question is: why the "up" button moves me to the MainActivity and not to the OtherActivity?
The Action Bar up navigation handler has been implemented in such a way that if the parent of current activity has no parent, then an Intent is created with ACTION_MAIN & CATEGORY_LAUNCHER to start the activity. This results in MainActivity being launched.
Have a look at definition of getParentActivityIntent() in Activity.java
To overcome this, in your ChildActivity.java override below 2 methods of Activity.
#Override
public boolean shouldUpRecreateTask(Intent intent) {
return true; // This creates a new task stack
}
#Override
public Intent getParentActivityIntent() {
Intent intent = new Intent(this, OtherActivity.class);
return intent;
}
If you don't want to override getParentActivityIntent, then you need to define a parent activity for OtherActivity in AndroidManifest.xml file, to overcome the earlier mentioned reason.
If you don't override shouldUpRecreateTask, since OtherActivity does not appear in history stack, it will remove all activities until the root activity of the task is reached, resulting in 'in-app home' behavior.

Android Phonegap screen rotation lock kills my app

i'm having problems with my application, i added an manifest that must prevent screen rotation but when i rotate the screen it kills the app.
Here is my code:
public class avantdroidActivity extends DroidGap {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
super.clearCache();
super.loadUrl("file:///android_asset/www/redir.html");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
My AndroidManifest.Xml:
<activity android:name="org.apache.cordova.DroidGap" android:label="#string/app_name" android:configChanges="keyboard|orientation|keyboardHidden"> <intent-filter> </intent-filter> </activity>
What im doing wrong? Thanks!
Why are you calling?
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
You can just set your activity orientation in your AndroidManifest.
Just add android:screenOrientation="portrait" to your activity tag.

How to set entire application in portrait mode only?

How do I set it so the application is running in portrait mode only? I want the landscape mode to be disabled while the application is running. How do I do it programmatically?
For any Android version
From XML
You can specify android:screenOrientation="portrait" for each activity in your manifest.xml file. You cannot specify this option on the application tag.
From Java
Other option is to do it programmatically, for example in an Activity base class:
#Override
public void onCreate(Bundle savedInstanceState) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
For Android 4+ (API 14+)
Last option is to do it with activity lifecycle listeners which is only available since Android 4.0 (API 14+). Everything happens in a custom Application class:
#Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleAdapter() {
#Override
public void onActivityCreated(Activity a, Bundle savedInstanceState) {
a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
});
}
ActivityLifecycleAdapter is just a helper class you'll need to create which will be an empty implementation of ActivityLifecycleCallbacks (so you don't have to override each and every methods of that interface when you simply need one of them).
Yes you can do this both programmatically and for all your activities making an AbstractActivity that all your activities extends.
public abstract class AbstractActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
This abstract activity can also be used for a global menu.
You can do this for your entire application without having to make all your activities extend a common base class.
The trick is first to make sure you include an Application subclass in your project. In its onCreate(), called when your app first starts up, you register an ActivityLifecycleCallbacks object (API level 14+) to receive notifications of activity lifecycle events.
This gives you the opportunity to execute your own code whenever any activity in your app is started (or stopped, or resumed, or whatever). At this point you can call setRequestedOrientation() on the newly created activity.
class MyApp extends Application {
#Override
public void onCreate() {
super.onCreate();
// register to be informed of activities starting up
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity,
Bundle savedInstanceState) {
// new activity created; force its orientation to portrait
activity.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
....
});
}
}
You can set this in your manifest file..
android:name=".your launching activity name"
android:screenOrientation="portrait"
and you can also achive the same by writing the code in your class file like:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Add android:screenOrientation="portrait" to the activity in the AndroidManifest.xml. For example:
<activity android:name=".SomeActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
Use:
android:screenOrientation="portrait"
Just write this line in your application's manifest file in each activity which you want to show in portrait mode only.
Write this to your manifest file, for every activity:
android:screenOrientation="portrait"
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting screen orientation locked so it will be acting as potrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
}
As from Android developer guide :
"orientation" The screen orientation has changed — the user has
rotated the device. Note: If your application targets API level 13 or
higher (as declared by the minSdkVersion and targetSdkVersion
attributes), then you should also declare the "screenSize"
configuration, because it also changes when a device switches between
portrait and landscape orientations.
"screenSize" The current available screen size has changed. This
represents a change in the currently available size, relative to the
current aspect ratio, so will change when the user switches between
landscape and portrait. However, if your application targets API level
12 or lower, then your activity always handles this configuration
change itself (this configuration change does not restart your
activity, even when running on an Android 3.2 or higher device). Added
in API level 13.
So, in the AndroidManifest.xml file, we can put:
<activity
android:name=".activities.role_activity.GeneralViewPagerActivity"
android:label="#string/title_activity_general_view_pager"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden|screenSize"
>
</activity>
Adding <preference name="orientation" value="portrait" /> under <widget> in my config.xml worked for me.
(The other solutions either didn't work on my device, were overwritten during building or gave deprecation errors during the build process.)
in Manifest file which activity you want to use in "portrait" you must write these code in Activity tag
android:screenOrientation="portrait"
like this
android:icon="#drawable/icon"
android:name="com.zemkoapps.hd.wallpaper.AndroidGridLayoutActivity"
android:screenOrientation="portrait" >
but if u want screen in landscape use this code like this
android:screenOrientation="landscape"
If anyone was wondering , how you could do this for your entire application without having to make all your activities extend a common base class in Kotlin ,
see the example below :
class InteractiveStoryApplication: Application() {
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(object: ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
override fun onActivityPaused(activity: Activity?) {
}
override fun onActivityResumed(activity: Activity?) {
}
override fun onActivityDestroyed(activity: Activity?) {
}
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
}
override fun onActivityStarted(activity: Activity?) {
}
override fun onActivityStopped(activity: Activity?) {
}
})
}
}
and then you have to add your common base class in AndroidManifest like so:
<application android:allowBackup="true"
android:name=".InteractiveStoryApplication"
You can do it in two ways .
Add android:screenOrientation="portrait" on your manifest file to
the corresponding activity
Add
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
to your activity in `onCreate() method
Similar to Graham Borland answer...but it seems you dont have to create Application class if you dont want...just create a Base Activity in your project
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
And extend this class instead of AppCompatActivity where you want to use Potrait Mode
public class your_activity extends BaseActivity {}
For Xamarin Users:
If you extends all your activities to a BaseActivity Just add:
this.RequestedOrientation = ScreenOrientation.Portrait;
This will resolve the problem. If you want any particular activity to be in landscape override this in OnActivityCreated. As:
this.Activity.RequestedOrientation = ScreenOrientation.Landscape;
Well,
I tried every answer but it didn't work in older versions of android.
So, the final solution is to add this code to every activity just above setContentView:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
In kotlin -->
Use this in your Extends Application class fun onCreate()...
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
override fun onActivityCreated(p0: Activity, p1: Bundle?) {
p0.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
}
override fun onActivityStarted(p0: Activity) {
}
override fun onActivityResumed(p0: Activity) {
}
override fun onActivityPaused(p0: Activity) {
}
override fun onActivityStopped(p0: Activity) {
}
override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
}
override fun onActivityDestroyed(p0: Activity) {
}
}
)}
In your Manifest type this:
<activity
android:screenOrientation="portrait"
<!--- Rest of your application information ---!>
</activity>

I want my android application to be only run in portrait mode?

I want my android application to be only run in portrait mode?
How can I do that?
In the manifest, set this for all your activities:
<activity android:name=".YourActivity"
android:configChanges="orientation"
android:screenOrientation="portrait"/>
Let me explain:
With android:configChanges="orientation" you tell Android that you will be responsible of the changes of orientation.
android:screenOrientation="portrait" you set the default orientation mode.
In Android Manifest File, put attribute for your <activity> that android:screenOrientation="portrait"
There are two ways,
Add android:screenOrientation="portrait" for each Activity in Manifest File
Add this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); in each java file.
in the manifest:
<activity android:name=".activity.MainActivity"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
or : in the MainActivity
#SuppressLint("SourceLockedOrientationActivity")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Old post I know. In order to run your app always in portrait mode even when orientation may be or is swapped etc (for example on tablets) I designed this function that is used to set the device in the right orientation without the need to know how the portrait and landscape features are organised on the device.
private void initActivityScreenOrientPortrait()
{
// Avoid screen rotations (use the manifests android:screenOrientation setting)
// Set this to nosensor or potrait
// Set window fullscreen
this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
DisplayMetrics metrics = new DisplayMetrics();
this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// Test if it is VISUAL in portrait mode by simply checking it's size
boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels );
if( !bIsVisualPortrait )
{
// Swap the orientation to match the VISUAL portrait mode
if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
{ this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
}
else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }
}
Works like a charm!
NOTICE:
Change this.activity by your activity or add it to the main activity and remove this.activity ;-)
Alternative solution is to set activity's orientation using ActivityLifecycleCallbacks.
import android.app.Activity
import android.app.Application
import android.content.pm.ActivityInfo
import android.os.Bundle
class App : Application() {
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
}
override fun onActivityStarted(activity: Activity) {}
override fun onActivityResumed(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, savedInstanceState: Bundle) {}
override fun onActivityDestroyed(activity: Activity) {}
})
}
}
Try this: (if SDK 23 & above)
Add your AndroidManifest.xlm;
<activity android:name=".YourActivity"
android:screenOrientation="locked"/>
like this.
in new SDk of android (24 and above) you can use in Manifest.xml in activity tag as you want:
<activity
android:name=".feature.main.MainActivity"
********* android:screenOrientation="locked" ******
android:configChanges="uiMode"
android:windowSoftInputMode="adjustPan"
android:exported="true">
and it work!
The accepted answer is correct. However, if you happen to be doing cross-platform development in C# using Uno Platform the Activity configuration is defined in an Activity attribute in the class. I'd expect this is the same if you're doing Xamarin or Xamarin Forms development.
Set:
ScreenOrientation = ScreenOrientation.Portrait
in the attribute parameters.
Here's an example within my MainActivity.cs class-level attribute:
[Activity(MainLauncher = true,
ConfigurationChanges = global::Uno.UI.ActivityHelper.AllConfigChanges,
WindowSoftInputMode = SoftInput.AdjustPan | SoftInput.StateHidden,
ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : Windows.UI.Xaml.ApplicationActivity { }
#unoplatform #xamarin #csharp #windows #crossplatform
I use
android:screenOrientation="nosensor"
It is helpful if you do not want to support up side down portrait mode.

Categories

Resources