getGSMSignalStrength() Always Returns 99 - java

I know there is another question on here relating to this, but I don't think it applies to me, as I'm pretty sure I use GSM (isGSM() returns true). In any case, getCdmaDbm returns -1 for me anyway. I am using Android 4.1.1 and an HTC One X. Here is my code (most of which isn't mine):
MainActivity:
package com.example.receptionlookup;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
TelephonyManager Tel;
MyPhoneStateListener MyListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Update the listener, and start it */
MyListener = new MyPhoneStateListener();
Tel = ( TelephonyManager )getSystemService(Context.TELEPHONY_SERVICE);
Tel.listen(MyListener ,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/* Called when the application is minimized */
#Override
protected void onPause()
{
super.onPause();
Tel.listen(MyListener, PhoneStateListener.LISTEN_NONE);
}
/* Called when the application resumes */
#Override
protected void onResume()
{
super.onResume();
Tel.listen(MyListener,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
/* —————————– */
/* Start the PhoneState listener */
/* —————————– */
private class MyPhoneStateListener extends PhoneStateListener
{
/* Get the Signal strength from the provider, each tiome there is an update */
#Override
public void onSignalStrengthsChanged(SignalStrength signalStrength)
{
super.onSignalStrengthsChanged(signalStrength);
Toast.makeText(getApplicationContext(), "Go to Firstdroid!!! GSM Cinr = "
+ String.valueOf(signalStrength.getGsmSignalStrength()), Toast.LENGTH_SHORT).show();
}
};/* End of private Class */
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.receptionlookup"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.receptionlookup.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
</manifest>
Does anyone know what the problem is? If I go to Settings->About->Network, I can see the signal strength there. Isn't there some way to just read this value? I've tried several third party apps, and none of them are able to read my signal strength either. I've also tried the proprietary getGSMSignalBar() method, but I get a NoSuchMethodException.

As you can read in the 3GPP 127 007 8.5 the implementation of the at+csq is optional (the command which suppose to give the signal strength). Apparently HTC hide this value from 3rd party applications and they probably have another way to achieve that value for display in their own proprietary Settings application.
The fact that other applications also cannot get that information justifies my case.
This issue is tightly related to yours - thay said that HTC is one of the OEMs that does not worth the modem related developing time.

Try this:
Class signalStrengthClass = signalStrength.getClass();
try {
Method method = signalStrengthClass.getMethod(
"getGsmSignalBar", null);
method.setAccessible(true);
Integer bars = (Integer) method.invoke(signalStrength,
(Object[]) null);
}
} catch (Exception e) {
e.printStackTrace();
}

Related

Android WebView geolocation

I know this question has been asked a lot of time but i could not find any help.
I am trying to built an app that loads a website that uses geolocation.
When the app loads, it should open up a google map with my location on it. On a web browser it works fine.
link i am trying to access is https://pas.irsglobal.net/test/
My code is as follows.
//MainActivity.java
package za.co.opexsolutions.www.panicapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
/**
* WebViewClient subclass loads all hyperlinks in the existing WebView
*/
public class GeoWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// When user clicks a hyperlink, load in the existing WebView
view.loadUrl(url);
return true;
}
}
/**
* WebChromeClient subclass handles UI-related calls
* Note: think chrome as in decoration, not the Chrome browser
*/
public class GeoWebChromeClient extends WebChromeClient {
#Override
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
// Always grant permission since the app itself requires location
// permission and the user has therefore already granted it
callback.invoke(origin, true, false);
}
}
WebView wv;
String mypage = "https://pas.irsglobal.net/test/";
String mypage_error = "file:///android_asset/mypage_error/index.html";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView) findViewById(R.id.wv);
wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv.setWebViewClient(new GeoWebViewClient());
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setGeolocationEnabled(true);
wv.setWebChromeClient(new GeoWebChromeClient());
wv.setFocusable(true);
wv.setFocusableInTouchMode(true);
wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
wv.getSettings().setDomStorageEnabled(true);
wv.getSettings().setDatabaseEnabled(true);
wv.getSettings().setAppCacheEnabled(true);
wv.setWebChromeClient(new WebChromeClient() {
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
// callback.invoke(String origin, boolean allow, boolean remember);
callback.invoke(origin, true, false);
}
});
wv.loadUrl(mypage);
wv.setWebViewClient(new WebViewClient(){
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
wv.loadUrl(mypage_error);
}
});
}
}
//Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
<uses-permission android:name="android.permission.LOCATION_HARDWARE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/shipping"
android:label="#string/app_name"
android:roundIcon="#mipmap/shipping"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".HomeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"></activity>
</application>
OK, After a some time of searching what could be the problem, I hope this will help others too.
The problem in this case it is not my code, but the Android version i was running on the emulator. (I was using Android 7 Nougat).
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.
If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request.
For full assistance Please Click Here

Where am I wrong with broadcasting info from Java and receiving in Unity?

So I just started working on this project and part of it is sending packages of information from an app in Java to another Unity app.
I have been trying to follow this tutorial but I have problems getting it to work and even somewhat understanding it a bit since I have not worked with Java before.
Here is the current code I have so far.
Main Activity Class
package com.example.service3;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
startService(new Intent(this, MyService.class));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Sender class
package com.example.service3;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
public class MyService extends Service
{
private final Handler handler = new Handler();
private int numIntent;
// It's the code we want our Handler to execute to send data
private Runnable sendData = new Runnable() {
// the specific method which will be executed by the handler
public void run() {
numIntent++;
// sendIntent is the object that will be broadcast outside our app
Intent sendIntent = new Intent();
// We add flags for example to work from background
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION|Intent.FLAG_FROM_BACKGROUND|Intent.FLAG_INCLUDE_STOPPED_PACKAGES );
// SetAction uses a string which is an important name as it identifies the sender of the itent and that we will give to the receiver to know what to listen.
// By convention, it's suggested to use the current package name
sendIntent.setAction("com.example.service3");
// Here we fill the Intent with our data, here just a string with an incremented number in it.
sendIntent.putExtra(Intent.EXTRA_TEXT, "Intent "+numIntent);
// And here it goes ! our message is send to any other app that want to listen to it.
sendBroadcast(sendIntent);
// In our case we run this method each second with postDelayed
handler.removeCallbacks(this);
handler.postDelayed(this, 1000);
}
};
#Override
public void onStart(Intent intent, int startid) {
numIntent = 0;
// We first start the Handler
handler.removeCallbacks(sendData);
handler.postDelayed(sendData, 1000);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
XML for Sender
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.service3"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.service3.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:enabled="true" android:name="com.example.service3.MyService" />
</application>
Receiver Class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class Receiver extends BroadcastReceiver
{
private static Receiver instance;
public static String text ="1";
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
String sentIntent = intent.getStringExtra(Intent.EXTRA_TEXT);
text = "-1";
}
public static void createInstance()
{
if(instance == null)
{
instance = new Receiver();
}
}
}
Unity Android Manifest
<application android:theme="#android:style/Theme.NoTitleBar.Fullscreen" android:icon="#drawable/app_icon" android:label="#string/app_name" android:debuggable="false" android:isGame="true" android:banner="#drawable/app_banner">
<activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="#string/app_name" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
<receiver android:name="com.example.receiver3.MyReceiver" >
<intent-filter>
<action android:name="com.example.receiver3" ></action>
</intent-filter>
</receiver>
</application>
I realise this is a massively large post but I simply do not know what to do at this point and am somewhat considering backing out of the project for the fact that I have no idea how to get Java to communicate with Unity.
Thanks in advance.

Function Isolating Camera's LED Light and java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera$Parameters

I am struggling to control the LED light next to my camera in the app I am trying to make for my own education purposes. I have tried to follow the methods in http://www.mkyong.com/android/how-to-turn-onoff-camera-ledflashlight-in-android/ , but I am trying to make the function more abstract and more general in order to increase reusable functionality and make the code more readable.
Upon creating my activity we first check, using PackageManager, that a LED camera does in fact exist. I then open the camera. The onClick function runs the functions changeScreen() and toggleLight(). Here you can see the clear advantages of using abstraction, ie toggleLight() works as a black box, using code set out elsewhere. The changeScreen function I know is correct, well before adding toggleLight() it was working correctly.
As the code should be correct, as it was taken from the example, I believe I have a problem with variable scope.
1) Where does the boolean isLighOn need to be declared, in the function or in the activity?
2) Same problem with the camera variable
How else should I go about creating an abstract function toggleLight()? I have checked around on this website, but a lot of posts send you to the link provided above. Moreover I believe an answer to this question would help many users and would provide reusable code.
Here is my code so far and I have posted the error I am getting below again.
package com.mycompany.myapplication;
import android.app.*;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Camera;
import android.os.*;
import android.util.Log;
import android.view.*;
import android.widget.*;
public class MainActivity extends Activity {
public RelativeLayout container;
private boolean isLighOn = false;
private Camera camera;
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = this;
PackageManager pm = context.getPackageManager();
// if device support camera?
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
return;
}
camera = Camera.open();
container = (RelativeLayout) findViewById(R.id.MainActivity);
container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeScreen(v);
toggleLight();
}
});
}
public void changeScreen(View v) {
ColorDrawable cd = (ColorDrawable) this.container.getBackground();
TextView ON = (TextView) findViewById(R.id.ON);
TextView OFF = (TextView) findViewById(R.id.OFF);
if (cd != null && cd.getColor() == getResources().getColor(R.color.BLACK)) {
container.setBackgroundColor(getResources().getColor(R.color.WHITE));
OFF.setVisibility(View.INVISIBLE);
ON.setVisibility(View.VISIBLE);
} else {
container.setBackgroundColor(getResources().getColor(R.color.BLACK));
OFF.setVisibility(View.VISIBLE);
ON.setVisibility(View.INVISIBLE);
}
}
public void toggleLight(){
final Camera.Parameters p = camera.getParameters();
if (isLighOn) {
Log.i("info", "torch is turn off!");
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLighOn = false;
} else {
Log.i("info", "torch is turn on!");
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLighOn = true;
}
}
}
When I load the app on my Android Studio emulator, I get the screen "ON". However, when you click the screen the app crashes. This is only error message I can find in the IDE. I am not sure how to interpret this error message.
In response to a comment below I am now posting the code containing the permissions.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.myapplication">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Don't rely on an emulator to produce reliable camera behavior. Always verify camera-related code on real device!

trying to understand Java activities by following a book

I am new to programming and I am trying to figure out how Activities in android programming work by making a small app,which should let me know in which state of the activity I am.
I am getting an error in the setContentView because Android Studio says "cannot resolve symbol "R""
Here is my code:
package com.example.daniele.activity;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
String tag = "Lifecycle";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(tag, "in the onCreate() event");
}
public void onStart() {
super.onStart();
Log.d(tag, "in the onStart() event");
}
public void onRestart() {
super.onRestart();
Log.d(tag, "in the onRestart() event");
}
public void onResume() {
super.onResume();
Log.d(tag, "in the onResume() event");
}
public void onPause() {
super.onPause();
Log.d(tag, "in the onPause() event");
}
public void onStop() {
super.onStop();
Log.d(tag, "in the onStop() event");
}
public void onDestroy() {
super.onDestroy();
Log.d(tag, "in the onDestroy() event");
}
}
here is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.daniele.activity" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Everyone is suggesting you the fix. Good. But since you are learning, you should also understand what is happening here:
All layout files are in xml
Every xml file is compiled and made available to java classes
The compiled class is called R.java
To make
R.java available to your class you need to import it
Under
import android.util.Log;
add this
import com.example.daniele.R;
Alternatively when you see a red underline under something, you can hover above it and Android Studio usually tells you what you need to do. In this case, "Optimize Imports" or something similar.
"R" errors usually happen when one or more of your XML files is corrupt. Start by seeing if your apps manifest looks correct!
You will need to import R because your activity is in a different package.
import com.example.daniele.R;

Application Class Null Pointer Exception

I am creating an Android app and wish to store a variable in the Application class. The variable signifies which Activity is currently in focus.
I aim to set this variable in onResume() and reset it in onPause(). Both methods are called as the app initialises. The software crashes on the basis of a Null Pointer Excepetion whenever I run my code, at lines where I try to modify the variable in the Application class. As far as I am aware, it appears to me as though the Application class is null even though I have tested the code and know it call the Application class' onCreate().
Am I correct in assuming it is connected to the Application Class not being completely created? Or is it connected to my instantiation of it all? I'm reasonably new to Android and haven't dealt with the Application class before - as far as I can see, I've followed the guides and tutorials correctly. I'm hoping it's a simple mistake.
Any and all advice is greatly appreciated!
MainActivity.java
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
//[... other initialisations...]
// Tells software what window is in focus.
// Reference to Application class
private MyApplicationClass app = (MyApplicationClass)getApplication();
private static final int outOfFocus = 0;
private static final int inFocus = 1;
#Override
protected void onResume() {
super.onResume();
//[... other code...]
app.setActivityFocusIndicator(inFocus); //Crashes here
}
#Override
protected void onPause() {
super.onPause();
//[... other code...]
app.setActivityFocusIndicator(outOfFocus); //Crashes here
}
}
MyApplicationClass.java
public class MyApplicationClass extends Application {
private int activityFocusIndicator;
/* activityFocusIndicator is here to indicate which activity is in focus.
* 0 = Nothing in focus (written when pausing.)
* 1 = MainActivity
* 2 = ...
* ...
*/
public void setActivityFocusIndicator(int activityFocusIndicator) {
this.activityFocusIndicator = activityFocusIndicator;
}
public int getActivityFocusIndicator() {
return activityFocusIndicator;
}
#Override
public void onCreate() {
super.onCreate();
Log.d("App", "App was created."); // This line is reached.
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.someApp"
android:versionCode="1"
android:versionName="1.0" >
<uses-feature android:name="android.hardware.bluetooth_le"
android:required="true"/>
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/TabTheme"
android:name="com.example.someName.MyApplicationClass" >
<activity
android:name="com.example.someName.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
...
</activity>
<!-- ... [other activities declared]... -->
<service
android:name=".BluetoothService"/>
</application>
</manifest>
I can post the LogCat if asked.
I don't see the point of this line :
private MyApplicationClass app = (MyApplicationClass)getApplication();
This variable is probably initialized before the reference returned by getApplication() is initialized, and therefore remains null.
Instead of using it, replace each acess to app with a local variable.
For example:
protected void onResume() {
super.onResume();
//[... other code...]
MyApplicationClass app = (MyApplicationClass)getApplication();
app.setActivityFocusIndicator(inFocus);
}

Categories