promixitylistner working even after unregistring it - service

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

Related

Unity 2020.3.38 crash onRequestPermissionsResult startActivityForResult

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

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.

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

java.lang.IllegalStateException: Content view not yet created

The "mMatchAdapter" is initialize at onCreate, but it is null in "setCursor", why?
This ListFragment is a tab of a tabHost, I use it to display list. I want change adapter in setCursor to display other list, but occur an error at line mMatchAdapter.changeCursor(c);
because mMatchAdapter is null, why? when getListView above this line, will
public class RecentsListFragment extends ListFragment implements onSetRecentsContactsCursor {
public final static String TAG = "RecentsListFragment";
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.d(TAG, "---------> onViewCreated ");
mListView = getListView();
Log.d(TAG, "onViewCreated------mListView = " + mListView);
mViewCreated = true;
setListShown(false);
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
Log.d(TAG, "---------> onDestroyView ");
mViewCreated = false;
super.onDestroyView();
}
#Override
public void onListItemClick(ListView l, View v, int pos, long id) {
// TODO Auto-generated method stub
Cursor cursor;
ListAdapter adapter = getListAdapter();
if (adapter == mLogsAdapter){
cursor = (Cursor)mLogsAdapter.getItem(pos);
}else if (adapter == mMatchAdapter){
cursor = (Cursor)mMatchAdapter.getItem(pos);
}
super.onListItemClick(l, v, pos, id);
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
Log.d(TAG, "------>onAttach");
mActivity = activity;
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.d(TAG, "---------> onCreate ");
mNumberQuery = NumberLocalQuery.getInstance(mActivity.getApplicationContext());
mQueryHandler = new CursorQueryHandler(mActivity.getContentResolver());
mPhotoLoader = new ContactPhotoLoader(mActivity);
mLogsAdapter = new BBKRecentCallsAdapter(mActivity, mPhotoLoader, mNumberQuery);
mMatchAdapter = new BBKDialerMatchListAdapter(mActivity, mPhotoLoader, mNumberQuery);
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
mCallsChanged = true;
Log.d(TAG, "---------> onStart ");
setListAdapter(mLogsAdapter);
mLogsAdapter.clearCache();
startQuery();
super.onStart();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
mCallsChanged = false;
Log.d(TAG, "---------> onStop ");
if (null != mQueryHandler){
mQueryHandler.cancelOperation(CUROSR_QUERY_TOKEN_CALLS);
}
super.onStop();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
Log.d(TAG, "---------> onResume ");
boolean is24Hour = DateFormat.is24HourFormat(mActivity);
if (null != mLogsAdapter){
mLogsAdapter.set24Hour(is24Hour);
}
if (null != mMatchAdapter){
mMatchAdapter.set24Hour(is24Hour);
}
mIsMatching = false;
super.onResume();
}
private void startQuery() {
Log.d(TAG, "---------> startQuery ");
if(mCallsChanged) {
Log.d(TAG, "start query call_log database");
mCallsChanged = false;
mQueryHandler.cancelOperation(CUROSR_QUERY_TOKEN_CALLS);
mQueryHandler.startQuery(CUROSR_QUERY_TOKEN_CALLS, null,
Calls.CONTENT_URI, RecentCallsListActivity.CALL_LOG_PROJECTION, null,
null, Calls.DEFAULT_SORT_ORDER);
}else if(mLogsAdapter != null && (mLogsAdapter.getCursor() != null)) {
mLogsAdapter.notifyDataSetChanged();
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.d(TAG, "---------> onActivityCreated ");
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.d(TAG, "---------> onDestroy ");
if (null != mLogsAdapter){
mLogsAdapter.clearCache();
mLogsAdapter.changeCursor(null);
}
if (null != mMatchAdapter){
mMatchAdapter.changeCursor(null);
}
super.onDestroy();
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
Log.d(TAG, "---------> onDetach ");
super.onDetach();
}
#Override
public void setCursor(Cursor c) {
// TODO Auto-generated method stub
Log.d(TAG, "====setCursor======mViewCreated====" + mViewCreated);
Log.d(TAG, "--------->mListView = " + mListView);
if (null != c && c.getCount() > 0){
setListAdapter(mMatchAdapter);
}
mMatchAdapter.changeCursor(c);
}
}

How to stop the onLocationChanged() in my LocationListener

How to stop the onLocationChanged() in my LocationListener , when i press the button ,the Toastbox in onLocationChanged keep coming out and can not stop even i leave the application.
Button btn_location =(Button) findViewById(R.id.button4);
btn_location.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
});
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitud = " + loc.getLatitude() + "Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
you can apply this:
mlocManager.removeUpdates(mlocListener);
to a button or put in onDestroy() or onPause()
Ref:Android Activity
The following code worked for me:
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
aLocationManager.removeUpdates(aLocationListener);
}
Just call removeUpdates() method wherever you want to stop update!