Android :: why getBooleanExtra java.lang.NullPointerException - java

PROBLEM
As topic mention, I don't know why getBooleanExtra() java.lang.NullPointerException.
I understand that sometimes intent may not contains extras.
However, from the below code as you can see there is a default value for each getBooleanExtra() which is false.
So, that's the reason why I don't understand. please advice. thx!
SOME CODE FROM MY SERVICE CLASS
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("onStartCommand()->","Intent Service.... " + intent);
final boolean SLEEP_MODE_ON = intent.getBooleanExtra("SLEEP_MODE_ON",false);
final boolean SLEEP_MODE_OFF = intent.getBooleanExtra("SLEEP_MODE_OFF",false);
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
connectIfNecessary();
if (SLEEP_MODE_ON){
doSleepMode_on();
} else if (SLEEP_MODE_OFF) {
doSleepMode_off();
}
}
});
thread.start();
return START_STICKY;
}
EDIT as some ask Where I call My service?? First, from activity. Second, from broadcastReceiver
ACTIVITY in onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
startService(new Intent(this,mqttPushService.class)); //Setup MQTT Service
}//END of onCreate()
BroadcastReceiver
public class SleepModeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent sleepModeIntent;
int broadcastID = intent.getIntExtra("BROADCAST_ID",0);
switch (broadcastID) {
case DataManager.BROADCAST_ID_SLEEP_MODE_START :
sleepModeIntent = new Intent(context, mqttPushService.class);
sleepModeIntent.putExtra("SLEEP_MODE_ON",true);
context.startService(sleepModeIntent);
break;
case DataManager.BROADCAST_ID_SLEEP_MODE_STOP :
sleepModeIntent = new Intent(context, mqttPushService.class);
sleepModeIntent.putExtra("SLEEP_MODE_OFF",true);
context.startService(sleepModeIntent);
break;
}
}
}

I ran into this recently. The issue is that even services can be killed and restarted by the system , thats why you have START_STICKY. Unlike when you start the service and you pass a valid intent, when the system restarts the service, the intent is null. I just check for a null intent before trying to extract any extras.
Here is the link to the official android developers blog.
http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html
and here is the paragraph which basically says what I say above
START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.

Related

Android service in own thread is killed together with app process

I have a service declared in manifest like
<service android:name=".services.ScreenOnService" android:process="#string/screenProcess"/>
all the service does is registering for Screen_on broadcast (As i always need the information that the Screen was turned on and not only if my app is running)
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//All this service has to do is register for the screen on broadcast
//as this one can't be registere in manifest and the ACTION_USER_PRESENT is
//not guaranteed to be fired. (E.g. if no lock screen is used)
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
registerReceiver(screenEventReceiver,filter);
return START_STICKY;
}
#Override
public void onDestroy()
{
unregisterReceiver(screenEventReceiver);
super.onDestroy();
}
I start the service from my Application onCreate
#Override
public void onCreate() {
super.onCreate();
if(!isScreenOnServiceAlreadyRunning())
{
//Start the screen on service
Intent screenOnService = new Intent(this, ScreenOnService.class);
startService(screenOnService);
}
}
Everything is fine as long as the app is running. If I kill the app, the service in it's own process is also killed and I don't get why.
I found a promising article here http://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android and hoped the best but even if I do this and send a broadcast, it will not work.
Why does the service stop working if the app is killed? I assumed it will keep running, as it's in it's own process. If what I want is not realisable with my approach, what's the best way to do so?
Thanks already.
#Hardcore_Graverobber I think you should start the service as a separate process,
please refer this tutorial
http://www.vogella.com/tutorials/AndroidServices/article.html

Service containing BroadCastReceiver not functioning correctly

Please see edits before answering!
I have an app which contains a BackgroundService class:
public class BackgroundService extends Service {
#Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction("com.spotify.music.playbackstatechanged");
filter.addAction("com.spotify.music.metadatachanged");
filter.addAction("com.spotify.music.queuechanged");
registerReceiver(receiver, filter);
Log.e("Playing:", "APP IS PLAYING");
Notification notification = new Notification();
startForeground(1, notification);
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long timeSentInMs = intent.getLongExtra("timeSent", 0L);
String action = intent.getAction();
if (action.equals(BroadcastTypes.METADATA_CHANGED)) {
String trackId = intent.getStringExtra("id");
String artistName = intent.getStringExtra("artist");
String albumName = intent.getStringExtra("album");
String trackName = intent.getStringExtra("track");
int trackLengthInSec = intent.getIntExtra("length", 0);
// Do something with extracted information...
} else if (action.equals(BroadcastTypes.PLAYBACK_STATE_CHANGED)) {
boolean playing = intent.getBooleanExtra("playing", false);
Log.e("Playing:","TRUE");
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
static final class BroadcastTypes {
static final String SPOTIFY_PACKAGE = "com.spotify.music";
static final String PLAYBACK_STATE_CHANGED = SPOTIFY_PACKAGE + ".playbackstatechanged";
static final String METADATA_CHANGED = SPOTIFY_PACKAGE + ".metadatachanged";
}
}
and this is declared in my manifest:
<service
android:name=".BackgroundService"
android:enabled="true" >
<intent-filter>
<action android:name="com.spotify.music.playbackstatechanged" />
<action android:name="com.spotify.music.metadatachanged" />
<action android:name="com.spotify.music.queuechanged" />
</intent-filter>
</service>
So essentially my objective is to have my BackgroundService initialized when my app is opened, and to have it continue to run in the Background doing whatever I need it to do. As of now, I am using logs to determine whether my "setup" is working, but when I run my app, I am unable to see an logs even after I tested all actions that should have triggered my BroadCastReceiver. Furthermore, my persistent notification should have changed had my service been running, but it does not...
Edit::
So, I added logs to my BackgroundService's onCreate() and onReceive() methods, however, neither seem to be appearing. Im wondering, do I need to do something in my launcher activity to initialize the service? Furthermore, no notification is shown so I assume the Service is not being started for some reason...
Latest Edit:
So I added the following code to my Main activity to see if it would make a difference:
startService(new Intent(this,BackgroundService.class));
And after debugging my app, I began to see the following error:
java.lang.RuntimeException: Unable to create service com.aurum.mutify.BackgroundService: java.lang.SecurityException: Isolated process not allowed to call registerReceiver
pointing to my BroadCast Receiver class.
Intent services are designed for short tasks. And your intent handling method is empty.
If you need long running task in the background use standard service and call start foreground. This will minimize chance of system destroying your service.
To learn more go here
EDIT
Try overriding onStartCommand method. this method is called when service is started and usually you do all stuff here. Remember that there are 3 options to return.
Edit 2:
try something like this
in on create
PendingIntent pi;
BroadcastReceiver br;
Intent myIntent;
#Override
public void onCreate()
{
super.onCreate();
myIntent = new Intent("something")
if(Build.Version.SDK_INT >= 16) //The flag we used here was only added at API 16
myIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
//use myIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); if you want to add more than one flag to this intent;
pi = PendingIntent.getBroadcast(context, 1, myIntent, 0);
br = new BroadcastReceiver ()
{
public void onReceive (Context context, Intent i) {
new thread(new Runnable()
{
public void run()
{
//do something
}
}).start();
}
};
And then in on start command
this.registerReceiver(br, new IntentFilter("something"));

Sending intents from service to activity only when activity is running

I have a service and application. There is communication between them by sending intents on specific situations. In activity I register and unregister broadcast receiver to collect this intents. Intents from service are sending when particular callback method is executed. Is there a possibility to send this intents only when activity is in the foreground? Because when this is hide there is no need to gather this intents (it helpful only to show some situations in real time)? I figure out that in activity could be static field that indicates about such situation, but I don't know how to get access to activity from service and additionally I found information that this is vary bad design practise.. Thank for any suggestions!
Declare this in your Activity:
public static boolean isRunning;
Then in your onPause to set isRunning = false;
and in onResume set it to isRunning = true;
Then from your Service you can simply call ActivityName.isRunning to know if it is in foreground or not!
you can use a static variable within the activity.
class MyActivity extends Activity {
static boolean active = false;
#Override
public void onStart() {
super.onStart();
active = true;
}
#Override
public void onStop() {
super.onStop();
active = false;
}
}
Add just check in service as
if(MyActivity.active)
{
//send broadcast.
}
OR
go with this to check status of activity is it active or not
public boolean isRunning(Context ctx) {
ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (RunningTaskInfo task : tasks) {
if (ctx.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName()))
return true;
}
return false;
}
I'd have a local boolean variable in service:
protected boolean mIsAppRunning;
Call startService() with true/false extra when app resumes/stops:
#Override
protected void onResume() {
super.onResume();
Intent service = new Intent("my.service.ACTION");
service.putExtra("IS_MY_ACTIVITY_RUNNING", true);
startService(service);
}
#Override
protected void onPause() {
Intent service = new Intent("my.service.ACTION");
service.putExtra("IS_MY_ACTIVITY_RUNNING", false);
startService(service);
}
Check that extra in service's onStartCommand() and assign its value to mIsAppRunning:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
mIsAppRunning = intent.getBooleanExtra("IS_MY_ACTIVITY_RUNNING", false);
}
return START_STICKY;
}
If you design the logic in the service a little carefully, you may even get rid of the local variable, mIsAppRunning, and call the required methods depending on the intent extra value.
Hope this helps.

NullPointerException when using getInt(String)

I'm android beginner so please be easy on me. I'm doing some "exercises" and i'm writing simple app which will tell RSSI strength of home wifi network. Getting that number is pretty easy, but updating it and showing that on screen it's a little more complicated as i thought.
First this is my onCreate Activity. In this activity i'm launching another android component - Service. Because the code will run in background (i know i could use thread or something else, but this is for "practice" sake, and i have a few ideas what to do with this app, while running service and not interacting with UI )
public class MainActivity extends Activity {
TextView wifi_check;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
referenceViews();
startService(new Intent(this, CheckingWifiService.class));
//wifi_check.setText(""+getIntent().getExtras().getInt("RSSI"));
}
private void referenceViews() {
wifi_check = (TextView) findViewById(R.id.wifiCheck_TV);
}
}
Because my code will run every second or so, i will use TimerTask for this purpose. And here is my TimerTask class, which includes run() method, and code for executing inside
public class TimerTsk extends TimerTask {
Context act;
WifiManager wifiMan;
WifiInfo info;
Bundle sendInfo;
Intent intent;
int rssi;
public TimerTsk(Context context) {
act = context;
}
#Override
public void run() {
intent = new Intent();
sendInfo = new Bundle();
wifiMan = (WifiManager) act.getSystemService(Activity.WIFI_SERVICE);
info = wifiMan.getConnectionInfo();
rssi = info.getRssi();
Log.d("WORKED", "RUNNING SUCESSFULLY");
// i want to send info to my activity
sendInfo.putInt("RSSI", rssi);
intent.putExtras(sendInfo);
}
}
From this class , i want to send result of RSSI to my activity and then update a text. But when i call this code below, on activity i always get NullPointerException.
wifi_check.setText(""+getIntent().getExtras().getInt("RSSI"));
To be honest i had hard time figuring out which part of code is throwing an exepction. And i found that more exactly, this part of code is throwing an exepction.
getInt("RSSI")
Overall i see that service is running, because in my LOGCAT i see a message that i create with Log.d in TimerTsk class.
Any ideas why is this happening?
Here is my service class:
public class CheckingWifiService extends Service{
int rssi;
Timer time;
TimerTsk ttsk;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
time = new Timer();
time.schedule(new TimerTsk(getApplicationContext()), 500);
return START_STICKY;
}
}
Here is my LogCat:
I see a common mistake. Don't do this:
sendInfo.putInt("RSSI", rssi);
intent.putExtras(sendInfo); // This adds a Bundle to your existing Bundle!
You are creating an Intent, with a Bundle of extras, with a Bundle that holds rssi. Leave out this unnecessary Bundle:
intent.putExtras("RSSI", rssi);
Now in your next Activity you can use:
getIntent().getIntExtra("RSSI", 0);
However you should always check to make sure there aren't any surprise null variables:
Intent in = getIntent();
if(in != null) {
int rssi = in.getIntExtra("RSSI", -1);
if(rssi < 0)
wifi_check.setText(""+rssi);
else
wifi_check.setText("Unknown");
}
is your activity starting? I don't see any call to startActivity(). In any case as mentioned by Sam you just need to call putExtra for your intent. don't forget to call
is your activity starting? I don't see any call to startActivity(). In any case as mentioned by Sam you just need to call putExtra for your intent. don't forget to call
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
you need to put this flag when start activies from background

Can I launch an activity from boot-up and have it go into the background without the user seeing it, android

At the moment I have code that starts an application from boot-up but opens it into the foreground.
This was done by
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent start = new Intent(context, ApolloMobileActivity.class);
start.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(start);
Then to get it sent to the background at boot-up I created another java file called, StartAtBootService
so I changed the receiver class to:
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent();
i.setAction("com.example.ssab.StartAtBootService");
context.startService(i);
}
And the Service class was
public class StartAtBootService extends Service
{
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
Log.v("StartServiceAtBoot", "StartAtBootService Created");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
/*
* In Android 2.0 and later, onStart() is depreciated. Use
* onStartCommand() instead, or compile against API Level 5 and
* use both.
* http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html
#Override
public void onStart(Intent intent, int startId)
{
Log.v("StartServiceAtBoot", "StartAtBootService -- onStart()");
}
*/
#Override
public void onDestroy()
{
Log.v("StartServiceAtBoot", "StartAtBootService Destroyed");
}
}
Is it possible to change the StartAtBootService to run an activity in another java file called ApolloMobileActivity in the background?
I have tested this code and even though it runs in the background at boot-up it doesn't run the code in ApolloMobileActivity.
Please help! Thanks guys :)
An Activity is an application component that provides a screen with
which users can interact in order to do something, such as dial the
phone, take a photo, send an email, or view a map. Each activity is
given a window in which to draw its user interface. The window
typically fills the screen, but may be smaller than the screen and
float on top of other windows.
from Activities
You can start an Activity, but there is no such thing as an invisible Activity. These are UI-components. If you want to do invisible work in the background, you have to do it in your service.

Categories

Resources