USB broadcast receiver (ACTION_POWER) not working - java

I am trying to implement a basic receiver for USB connection. Found a reference here.
I searched a lot, but can't make it to work...
package com.example.usbtethering;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "USB connected.", Toast.LENGTH_SHORT).show();
Log.v("AAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAA");
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.usbtethering">
<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/Theme.USBTethering">
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/Theme.USBTethering.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
</application>
</manifest>
On emulator, I am changing the following setting:
I see the status is changing on the phone bar, but my code is not executed.
Any idea what I am missing?
TL;DR (XY)
My goal is to enable USB tethering automatically when connected to USB, only if hour is between 8:00-22:00. The idea is to block internet usage outside of the specified hours.
On the phone - settings, app-store, browsers, Youtube and hotspot are password locked. So the internet can only be used for Whatsapp, waze, and USB tethering. However this currently requires the "administrator" to manually enable/disable USB tethering in settings each time.
So I intend to create this app which I think should be simple, give it permission to change settings:
Enable tethering on each USB connection between 8:00 and 22:00.
Disable tethering (if enabled) on 22:00.
I have moderate C++/python programming experience, and some Java, but this is my first attempt to Android.

As part of the Android 8.0 (API level 26) Background Execution Limits,
apps that target the API level 26 or higher can no longer register
broadcast receivers for implicit broadcasts in their manifest.
However, several broadcasts are currently exempted from these
limitations. Apps can continue to register listeners for the following
broadcasts, no matter what API level the apps target.
So from the API > 28 Version you must register the reciver for that you can use this piece of code in your Activity or if you want to listen to the Power Connection changes in the background use a Service
IntentFilter ACTION_POWER_CONNECTED = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
IntentFilter ACTION_POWER_DISCONNECTED = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
registerReceiver(new MyReceiver(), ACTION_POWER_CONNECTED);
registerReceiver(new MyReceiver(), ACTION_POWER_DISCONNECTED);
I believe you want to use a Service this is an example :
First you need to Create a Service (PowerSerivce) in the manifest file :
<service
android:name=".PowerService"
android:stopWithTask="false" />
<!-- If set to true,
this service with be automatically stopped when the user remove a task rooted in an activity owned by the application-->
And this is the PowerService.java :
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
public class PowerService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter ACTION_POWER_CONNECTED = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
IntentFilter ACTION_POWER_DISCONNECTED = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
registerReceiver(new MyReceiver(), ACTION_POWER_CONNECTED);
registerReceiver(new MyReceiver(), ACTION_POWER_DISCONNECTED);
Log.d("Service", "onStartCommand: " );
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("Service", "onDestroy: " );
}
}
And this is MyReciver :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.ACTION_POWER_CONNECTED")){
Toast.makeText(context, "CONNECTED", Toast.LENGTH_LONG).show();
}else if(intent.getAction().equals("android.intent.action.ACTION_POWER_DISCONNECTED")){
Toast.makeText(context, "DISCONNECTED", Toast.LENGTH_LONG).show();
}
}
}
And finaly you need to start this Service in my case i started it only for API>=26
normally in APIs below 26 you don't need this Service (you can check it by yourself). in this code I started the PowerService only for version above API 26
// add this code in your first activity or where you want
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startService(new Intent(this, PowerService.class)):
}
References :
Service
Implicit Broadcast
Exceptions

Related

How to start activity or service (Either) on bootup completed?

I'm trying to find out how to run a service (Any service, may be foreground or background) when device boots. I've tried implementing broadcast receiver but it seems not to work.
Below is my full code.
1.AndroidManifext.xml - I made sure I included the service and broadcast receiver here. Are there any permissions I may be lacking?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.testboot">
<!-- Example need below permission. -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name="com.example.testboot.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.example.testboot.BootDeviceReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service
android:name="com.example.testboot.RunAfterBootService"
android:enabled="true"
android:exported="true"></service>
</application>
</manifest>
2.MainActivity.java - This is the launch class, I made it call the broadcast receiver class. Asides from that, it doesn't have anything else.
package com.example.testboot;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("com.example.testboot.BootDeviceReceiver");
sendBroadcast(intent);
}
}
3.BootDeviceReceiver.java -This is the class responsible for knowing when device has booted up (Extends Broadcast receiver)
package com.example.testboot;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class BootDeviceReceiver extends BroadcastReceiver {
private static final String TAG_BOOT_BROADCAST_RECEIVER = "BOOT_BROADCAST_RECEIVER";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String message = "BootDeviceReceiver onReceive, action is " + action;
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_BROADCAST_RECEIVER, action);
if(Intent.ACTION_BOOT_COMPLETED.equals(action))
{
//startServiceDirectly(context);
startServiceByAlarm(context);
}
}
/* Start RunAfterBootService service directly and invoke the service every 10 seconds. */
private void startServiceDirectly(Context context)
{
try {
while (true) {
String message = "BootDeviceReceiver onReceive start service directly.";
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_BROADCAST_RECEIVER, message);
// This intent is used to start background service. The same service will be invoked for each invoke in the loop.
Intent startServiceIntent = new Intent(context, RunAfterBootService.class);
context.startService(startServiceIntent);
// Current thread will sleep one second.
Thread.sleep(10000);
}
}catch(InterruptedException ex)
{
Log.e(TAG_BOOT_BROADCAST_RECEIVER, ex.getMessage(), ex);
}
}
/* Create an repeat Alarm that will invoke the background service for each execution time.
* The interval time can be specified by your self. */
private void startServiceByAlarm(Context context)
{
// Get alarm manager.
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Create intent to invoke the background service.
Intent intent = new Intent(context, RunAfterBootService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long startTime = System.currentTimeMillis();
long intervalTime = 60*1000;
String message = "Start service use repeat alarm. ";
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_BROADCAST_RECEIVER, message);
// Create repeat alarm.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime, intervalTime, pendingIntent);
}
}
3.RunAfterBootService.java - This is the service class, should be displayed after device completes booting up.
package com.example.testboot;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
public class RunAfterBootService extends Service {
private static final String TAG_BOOT_EXECUTE_SERVICE = "BOOT_BROADCAST_SERVICE";
public RunAfterBootService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG_BOOT_EXECUTE_SERVICE, "RunAfterBootService onCreate() method.");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String message = "RunAfterBootService onStartCommand() method.";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_EXECUTE_SERVICE, "RunAfterBootService onStartCommand() method.");
Intent i = new Intent();
i.setClass(RunAfterBootService.this,MainActivity.class);
startActivity(i);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
So far, when I restart my device nothing happens at all.
Has your app an icon ? you must open your app one time then you can receive the boot_complete broadcast.

How to receive ACTION_SCREEN_OFF with a "always running" service

I want to create an app that set/reset a timer to reproduce a song if the mobile spend 8 hours with the screen off.
I want to create a service that receive ACTION_SCREEN_OFF, but the problem is that when the app is killed from recent apps, the service is killed. I try with START_STICKY but the service is not restarted (onCreate is called sometimes but not onStart Command). I try to set in Manifest but the receiver must be register.
By now I only want that receiver detect ACTION_SCREEN_OFF.
I Have this code:
MainScreen.java (MainActivity)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainScreen extends Activity implements View.OnClickListener{
public static final String MSG_TAG = "NoSleepMore";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
findViewById(R.id.start_service_button).setOnClickListener(this);
findViewById(R.id.stop_service_button).setOnClickListener(this);
}
#Override
public void onClick(View v){
Intent intent = new Intent(getApplicationContext(), LockService.class);
switch (v.getId()) {
case R.id.start_service_button:
Log.e(MSG_TAG,"Service started");
//starts service for the given Intent
startService(intent);
break;
case R.id.stop_service_button:
Log.e(MSG_TAG,"Service stopped");
//stops service for the given Intent
stopService(intent);
break;
}
}
}
LockService.java
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
public class LockService extends Service {
#Override
public IBinder onBind(Intent arg0) {
Log.i(MainScreen.MSG_TAG, "onBind()" );
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(MainScreen.MSG_TAG, "Service Created");
/* Filtrar Acciones Capturadas */
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
// Listener
final BroadcastReceiver mReceiver = new ScreenReceiver();
// Registar Listener
registerReceiver(mReceiver, filter);
return Service.START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
Log.i(MainScreen.MSG_TAG, "onCreate()");
}
#Override
public void onDestroy() {
Log.i(MainScreen.MSG_TAG, "onDestroy()");
}
}
ScreenRecive.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
Log.i(MainScreen.MSG_TAG,"OnReceive->");
// Log Handel
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
Log.i(MainScreen.MSG_TAG,"Screen action OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
Log.i(MainScreen.MSG_TAG,"Screen action ON");
}else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
Log.e(MainScreen.MSG_TAG,"Action UserPresent");
}
}
}
AndroidManifext.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="es.mangel.nosleepmore">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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=".MainScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_SCREEN_ON"/>
<action android:name="android.intent.action.ACTION_SCREEN_OFF"/>
<action android:name="android.intent.action.ACTION_USER_PRESENT"/>
</intent-filter>
</receiver>
<service android:name=".LockService" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</service>
</application>
</manifest>
The Main activity is just two buttons.
BTW I just need that run over Android 8.0.

how to override permission manager in android

i m creating app that has permission to autostart with boot. and it is working fine on those mobile that does not contains Permission manager.
i want to start my app like Whats App and Wechat and other app does. But permission manager stop my app to auto start - MI Redme Note 4g mobile and Samsung mobile. Basically, i want to override the permission manager setting so that my app will start
currently i m using these code
<receiver
android:name=".BootComplete"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".AutoStartUp" >
</service>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Please Advice me to get my app auto start like Whats App, Wechat, Youtube and Other app does
thanks in Advance
What your code does here is that: When the device is booted it will tell the broadcast receiver, now the broadcast receiver needs to start the Service or App or whatever you want to start:
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent0) {
if(! isMyServiceRunning(MyFirstService.class, context)){//test
Intent startServiceIntent = new Intent(context, MyFirstService.class);
context.startService(startServiceIntent);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass,Context context) {
ActivityManager manager = (ActivityManager)context. getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
This code also checks if the Service is already running (for some reason) and you can remove that part if you want.

Android – Background Service does not run if Phone is Asleep

I am trying to make an application for my school that includes a background service that will download a student's grades, and assignment history. The service is called every hour by an AlarmManager, and it works, but only as long as the device is powered on. As soon as the device is turned on (from a state of hibernation; the device is not completely shut down), the AlarmManager triggers the service. This is the code of the BroadcastReceiver, which includes the AlarmManager:
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.support.v4.content.WakefulBroadcastReceiver;
public class ServiceAlarmReceiver extends WakefulBroadcastReceiver {
private final String TAG = "com.example.ahsandroidapplication";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Broadcast received");
Intent gradeNotificationServiceIntent = new Intent(context, GradeNotificationService.class);
//context.startService(gradeNotificationServiceIntent);
startWakefulService(context, gradeNotificationServiceIntent);
}
public static void setAlarm(Context context){
System.out.println("Service started");
long alertTime = System.currentTimeMillis() + 1000 * 60 * 60;
Intent alertIntent = new Intent(context, ServiceAlarmReceiver.class);
alertIntent.setAction("com.example.ahsandroidapplication.servicealarmbroadcast");
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, PendingIntent.getBroadcast(context, 1, alertIntent,
// PendingIntent.FLAG_UPDATE_CURRENT));
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alertTime, 1000 * 3600, PendingIntent.getBroadcast(context,
GradeNotificationService.SERVICE_ALARM_BROADCAST_ID, alertIntent,
PendingIntent.FLAG_UPDATE_CURRENT));
}
public static void cancelAlarm(Context context)
{
Intent intent = new Intent(context, ServiceAlarmReceiver.class);
intent.setAction("com.example.ahsandroidapplication.servicealarmbroadcast");
PendingIntent sender = PendingIntent.getBroadcast(context,
GradeNotificationService.SERVICE_ALARM_BROADCAST_ID, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
Because the broadcast is received only when the phone is turned on, I believe the problem lies in the receiver.
There is another problem with the service. It is supposed to send a push notification whenever a new grade is posted, but they are never being sent.
Here is the code for the service class:
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.NotificationCompat;
public class GradeNotificationService extends IntentService {
private Context context;
public GradeNotificationService() {
super("GradeNotificationService");
// TODO Auto-generated constructor stub
}
public static final int SERVICE_ALARM_BROADCAST_ID = 0;
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
System.out.println("Grade notification services started");
context = getApplicationContext();
final Intent completeWakefulIntent = intent;
if(gradesChanged()){
getAssignments();
}
ServiceAlarmReceiver.completeWakefulIntent(completeWakefulIntent);
}
private boolean gradesChanged() {
//Massive blocks of code that will take you forever to read
}
private void getAssignments(){
//Massive blocks of code that will take you forever to read
//It is in this method that sendNotification() is used to send a notification
//(at least that's what it's supposed to be doing)
}
private void sendNotification(String title, String message){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setContentTitle(title);
mBuilder.setContentText(message);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
Intent resultIntent = new Intent(context, MainInterface.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(1, mBuilder.build());
}
private boolean networkIsAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
// return netInfo != null && netInfo.isConnectedOrConnecting();
NetworkInfo mWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return netInfo != null && netInfo.isConnectedOrConnecting()
|| mWifi.isConnected();
}
}
Can anyone tell me what I can do to make this service run when the phone is asleep, or why it is not sending any notifications? Any help is appriciated.
Edit:
This is most of the manifest. The target sdk is 21 and the minimum is 11:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:label="#string/app_name"
android:icon="#drawable/ic_launcher">
<service
android:name="com.example.ahsandroidapplication.GradeNotificationService"
android:enabled="true" >
<intent-filter>
<action android:name="com.example.ahsandroidapplication.ServiceAlarmReceiver" />
</intent-filter>
</service>
<receiver android:name=".ServiceAlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="com.example.ahsandroidapplication.servicealarmbroadcast"></action>
</intent-filter>
</receiver>
<receiver android:name=".BootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
<activity
android:name="MainInterface"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="MainLogin"
android:label="#string/app_name">
</activity>
<service android:enabled="true"
android:exported="false"
android:isolatedProcess="false"
android:label="#string/app_name"
android:name="AspenManager" >
</service>
</application>
"Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested."
http://developer.android.com/reference/android/app/AlarmManager.html

getGSMSignalStrength() Always Returns 99

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();
}

Categories