Unity 2020.3.38 crash onRequestPermissionsResult startActivityForResult - unity3d

public class MyActivity extends UnityPlayerActivity {
private MyActivity activity;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
}
public void open() throws Exception{
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
111);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Intent openAlbumIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
try {
activity.startActivityForResult(openAlbumIntent, 111);
} catch (Exception e) {
e.printStackTrace();
}
// (new TimerTask() {
// #Override
// public void run() {
// Intent openAlbumIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
// try {
// activity.startActivityForResult(openAlbumIntent, 111);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// },100);
}
}
Start activity in onRequestPermissionsResult
It crashes after a few tries
it happend on unity 2020.3.38, but on 2020.3.33 it's ok
if MyActivity extends Activity not UnityPlayerActivity, it's ok
if start activity delay 100ms by a TimerTask, it's ok
why why why
unity 2022.1.23 not ok
unity 2020.3.42 not ok
unity 2020.3.38 ok.
why why why

Related

Interstitial ads for coco2d android game

I'm facing a lot of difficulties to show the Interstitial, it's my first time working with the Cocos2D game.
This is all main java code
public class FlyingPanda extends Activity implements AdListener {
/** Called when the activity is first created. */
public static CCGLSurfaceView mGLSurfaceView;
private boolean isCreated = false;
private static final String ADMOB_PUBLISH_ID = "xxxxxxxxxxxxxxxxxx";
#Override
public void onCreate(Bundle savedInstanceState) {
if( !isCreated ){
isCreated = true;
} else {
return;
}
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
RelativeLayout layout = new RelativeLayout(this);
layout.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mGLSurfaceView = new CCGLSurfaceView(this);
// Create the adView
AdView adView = new AdView(this, AdSize.BANNER, ADMOB_PUBLISH_ID);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
adView.setAdListener(this);
// Add the adView to it
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
adView.setLayoutParams(params);
layout.addView(mGLSurfaceView);
layout.addView(adView);
setContentView(layout);
Common.game_initialize();
getScaledCoordinate();
CCDirector.sharedDirector().attachInView(mGLSurfaceView);
// attach the OpenGL view to a window
Common.sound_engine = SoundEngine.sharedEngine();
loadSound();
What am I supposed to add here in admob setting? I'll define a variable named interstitial like the banner or what?
////////////////////////////////////////////////////////////////////////////////
// Admob Setting
////////////////////////////////////////////////////////////////////////////////
How can I Load interstitial in all this public classes?
#Override
public void onDismissScreen(Ad ad) {
// TODO Auto-generated method stub
}
#Override
public void onFailedToReceiveAd(Ad ad, ErrorCode errorCode) {
// TODO Auto-generated method stub
}
#Override
public void onLeaveApplication(Ad ad) {
// TODO Auto-generated method stub
}
#Override
public void onPresentScreen(Ad ad) {
// TODO Auto-generated method stub
}
#Override
public void onReceiveAd(Ad ad) {
MainActivity.java:
public class AppActivity extends Cocos2dxActivity {
private static final String ADMOB_INTERSTITIAL = "ca-app-pub-2575683230512628/5833084223";
private InterstitialAd admobInterstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_appActivity = this;
admobInterstitial = new InterstitialAd(this);
admobInterstitial.setAdUnitId(ADMOB_INTERSTITIAL);
admobInterstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
admobInterstitial.loadAd(newAdRequest());
}
});
admobInterstitial.loadAd(newAdRequest());
}
public static void showInterstitial(final String adSdk){
Log.d("ADMOB INTERSTITIAL", "showInterstitial: " + adSdk);
_appActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if(adSdk.equalsIgnoreCase("admob")){
if(_appActivity.admobInterstitial != null){
if(_appActivity.admobInterstitial.isLoaded()){
_appActivity.admobInterstitial.show();
}
}
}
else if(adSdk.equalsIgnoreCase("chartboost")){
}
else if(adSdk.equalsIgnoreCase("revmob")){
}
else{
Log.w("INTERSTITIAL", "unknown ad to show: " + adSdk);
}
}
});
}
private AdRequest newAdRequest(){
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("YOUR_DEVICE_ID")
.build();
return adRequest;
}
}
c++ code (.c file):
const char* AppActivityClassName = "org/cocos2dx/cpp/AppActivity";
bool NativeHelper::instanceFlag = false;
NativeHelper* NativeHelper::instance = NULL;
NativeHelper* NativeHelper::getInstance(){
if(!instanceFlag){
instance = new NativeHelper();
instanceFlag = true;
}
return instance;
}
void NativeHelper::showInterstitial(string adSdk){
cocos2d::JniMethodInfo t;
if (cocos2d::JniHelper::getStaticMethodInfo(t, AppActivityClassName, "showInterstitial", "(Ljava/lang/String;)V")){
jstring stringArg = t.env->NewStringUTF(adSdk.c_str());
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg);
}
}
c++ code (.h file):
class NativeHelper
{
public:
static void showInterstitial(string adSdk);
private:
static bool instanceFlag;
static NativeHelper* instance;
}
You can also use SDKBOX, but this is more flexible solution and you always have up-to-date sdk.

How to show reign of area using SurfaceView and SurfaceHolder?

I would like to know if there is a way to show only a reign of area of the camera that shown on a SurfaceView.
I've got an image like that (microscopic image)
and I want to show image like that(Cropped and Stretched):
This is a part of my code(it is a basic code that show the camera on SurfaceView using SurfaceHolder):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_sample_testing);
overridePendingTransition(0, 0);
cameraView = (SurfaceView)findViewById(R.id.CameraView);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
//parameters.setZoom(10);
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
camera.setDisplayOrientation(90);
camera.startPreview();
camera.autoFocus(autoFocusCallback);
recorder = new MediaRecorder();
final Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
StartTest(0);
myTimer.cancel();
myTimer.purge();
}
},10000, 10);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void initRecorder() {
camera.unlock();
recorder.setCamera(camera);
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setMaxDuration(50000); // 50 seconds
recorder.setMaxFileSize(300000000); // Approximately 5 megabytes
recorder.setOutputFile(VIDEO_PATH);
}
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
Thanks for any help!

Mirror the preview

public class AndroidCamera extends Activity implements SurfaceHolder.Callback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;;
EditText txtData;
String stringPath = "/sdcard/samplevideo.3gp";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStartCameraPreview = (Button)findViewById(R.id.startcamerapreview);
Button buttonStopCameraPreview = (Button)findViewById(R.id.stopcamerapreview);
txtData = (EditText) findViewById(R.id.editText1);
//txtData.setText("DD");
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
buttonStartCameraPreview.setOnClickListener(new Button.OnClickListener(){
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!previewing){
camera = Camera.open(0);
if (camera != null){
txtData.setText("CamOk");
try {
//txtData.setText("DD");
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else txtData.setText("null");
}
}});
buttonStopCameraPreview.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(camera != null && previewing){
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.android_camera, menu);
return true;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
I am trying to preview the image using a front-facing camera. But the preview is mirrored. How can I mirror it again so that i can preview a non-mirrored preview. Please help, I have been searching this for days

Progress Dialog on Rajawali Vuforia example

It is possible to show progress dialog when loading the .obj model. I tried to call the ProgressDialog in RajawaliVuforiaExampleRenderer.java but it said "Can't create handler inside thread that has not called Looper.prepare()"
I have pasted part of the code here:
protected void initScene() {
mLight = new DirectionalLight(.1f, 0, -1.0f);
mLight.setColor(1.0f, 0, 0);
mLight.setPower(1);
getCurrentScene().addLight(mLight);
LoaderOBJ objParser = new LoaderOBJ(mContext.getResources(),
mTextureManager, R.raw.wall_obj);
try {
// Load model
objParser.parse();
wall = objParser.getParsedObject();
addChild(wall);
} catch (Exception e) {
e.printStackTrace();
}
}
EDITED:
I have read the comment from Abhishek Agarwal and updated the code for Renderer part, now i having problem on calling the ProgressDialog when loading the model, here is my code for the UI thread.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// receive file path
String filePath = this.getIntent().getStringExtra("FullFilePath");
Log.i(filePath, "FullFilePath:" + filePath);
waitDialog = ProgressDialog.show(this, "", "Loading", true);
waitDialog.show();
new ModelLoader().execute();
}
#Override
protected void setupTracker() {
int result = initTracker(TRACKER_TYPE_MARKER);
if (result == 1) {
result = initTracker(TRACKER_TYPE_IMAGE);
if (result == 1) {
super.setupTracker();
} else {RajLog.e("Couldn't initialize image tracker.");
}
} else {
RajLog.e("Couldn't initialize marker tracker.");
}}
protected void initApplicationAR() {
super.initApplicationAR();
createImageMarker("marker.xml");
}
protected void initRajawali() {
super.initRajawali();
mRenderer = new ModelRenderer(this);
mRenderer.setSurfaceView(mSurfaceView);
super.setRenderer(mRenderer);
mUILayout = this;
mUILayout.setContentView(mLayout, new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
private class ModelLoader extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
startVuforia();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
waitDialog.dismiss();
}
}
Progress Dialog can be shown on the UIThread. So show progress dialog on the main thread not under GLThread
You can use Handler to be on threadUI :
`private Handler mHandler = new Handler();
...
mHandler.post(new Runnable() {
#Override
public void run() {
view_progressBar.setProgress(val);
}
});`

promixitylistner working even after unregistring it

I am devolping an application which turns the screen off and on based proximity sensor. The code i wrote sucessful turns the screen off and on.
This is the acivity from which the proximity sensors are registed and unregistered
MainActivity.java
public class MainActivity extends Activity {
public String TAG = "MainActivity";
BackgroundService mService;
boolean mBound = false;
boolean firstTime = true;
Intent BackgroundIntent ;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
Log.w(TAG, "Service Disconeted");
mBound = false;
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
LocalBinder binder = (LocalBinder)service;
mService = binder.getService();
mBound=true;
if(firstTime){
MainActivity.this.onStart();
}
firstTime = false;
Log.w(TAG, "Service Connectedd");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.w(TAG, "onCreate()");
setContentView(R.layout.activity_main);
Button buttonStart = (Button)findViewById(R.id.button1);
Button buttonStop = (Button)findViewById(R.id.button2);
buttonStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mService.enableSensor();
Log.w(TAG, "ButtonStart Clicked");
}
});
buttonStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mBound){
mService.disableSensor();
}
Log.w(TAG, "ButtonSTOP Clicked");
}
});
startService(new Intent(this,BackgroundService.class));
}
#Override
public void onStart(){
super.onStart();
Log.w(TAG, "onStart Method");
Intent intent = new Intent(getApplicationContext(),BackgroundService.class);
getApplicationContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop(){
super.onStop();
if(mBound){
getApplicationContext().unbindService(mConnection);
Log.w(TAG, "Unbinding the service");
}
Log.w(TAG, "onStop Method");
}
}
This is the service which has a SensorEventListner which which listens to the changes in the proximity sensor
BackgroundService.java
public class BackgroundService extends Service{
public String TAG = "BackgroundService";
private final IBinder mBinder = new LocalBinder();
private SensorManager mSensorManager ;
private Sensor mProximitySensor ;
private SensorEventListener mSenosorEventListener;
private PowerManager.WakeLock proximityWakeLock;
public float maxSensorValue;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.e(TAG, "Binding with backgroundService");
return mBinder;
}
public class LocalBinder extends Binder{
BackgroundService getService(){
return BackgroundService.this;
}
}
#Override
public void onCreate(){
Log.w(TAG, "BackgroundService Created");
proximityWakeLock = ((PowerManager)getSystemService("power")).newWakeLock(32, "");
proximityWakeLock.setReferenceCounted(false);
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
maxSensorValue = mProximitySensor.getMaximumRange();
mSenosorEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.sensor.getType() == Sensor.TYPE_PROXIMITY ){
if(event.values[0] == maxSensorValue)
{
Log.w(TAG, "Object moved ****AWAY*****");
screanTurnOn();
}
else{
Log.w(TAG, "Object moved ****NEAR******");
screanTurnOFF();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Sensor Accuracy Changed", Toast.LENGTH_SHORT).show();
}
};
}
#Override
public void onDestroy(){
mSensorManager.unregisterListener(mSenosorEventListener);
Log.w(TAG, "BackgroundService is Destroyed");
super.onDestroy();
}
public void screanTurnOFF(){
if(proximityWakeLock.isHeld()){
this.proximityWakeLock.release();
Log.e(TAG,"WakeLock is released");
}
}
public void screanTurnOn(){
if(!proximityWakeLock.isHeld())
proximityWakeLock.acquire();
while(proximityWakeLock.isHeld()){
Log.e(TAG, "WakeLock is acurqerd");
return;
}
}
public void enableSensor(){
if(mProximitySensor == null){
Log.w(TAG, "No Proximity detector found");
}else{
mSensorManager.registerListener(mSenosorEventListener, mProximitySensor,SensorManager.SENSOR_DELAY_NORMAL);
Log.w(TAG, "Proximity detector Enabled : "+ mProximitySensor.getName());
}
}
public void disableSensor(){
mSensorManager.unregisterListener(mSenosorEventListener,mProximitySensor);
Log.w(TAG, "Proximity Detector Disabled : " + EnableProximitySensor);
}
}
I have two buttons, one that registers the SensorEventListner to the sensor manager, and one to unregister it. The first button works perfectly. When i click on the second button, the ProximityEventListen remain unregistered.The sensoEventLister still works but the app will not show any Log messages from the BackGroundService.
If i comment out the screenTurnON() and screenTurnOFF() functions, the code works perfectly.
Please Help me out