I'm using the following code in my service:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mStartId = startId;
handleStartCommandIntent(intent);
return START_REDELIVER_INTENT;
}
private void handleStartCommandIntent(#Nullable Intent intent) {
if (mCompositeDisposable == null) {
mCompositeDisposable = new CompositeDisposable();
}
checkNotNull(intent, "intent cannot be null");
String type = intent.getStringExtra(SERVICE_REQUEST_TYPE);
<...>
}
#Override
public void completed() {
stopSelf(mStartId);
}
checkNotNull is the first point where intent is looked at, however I'm not seeing my custom message in the stack trace. The check method looks as following:
public static <T> T checkNotNull(T reference, #Nullable Object errorMessage) {
if(reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
} else {
return reference;
}
}
However, I'm still seeing an NPE in my Crashlytics logs:
Fatal Exception: java.lang.RuntimeException: Unable to start service com.myapp.app.internal.service.MessagingService#4134a7b8 with Intent { cmp=com.myapp.app/com.myapp.app.internal.service.MessagingService }: java.lang.NullPointerException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2608)
at android.app.ActivityThread.access$1900(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4847)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:535)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by java.lang.NullPointerException
at com.myapp.app.internal.service.MessagingService.onStartCommand(MessagingService.java:1065)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2591)
at android.app.ActivityThread.access$1900(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4847)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:535)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(NativeStart.java)
According to the docs my service should never receive a call with a null intent:
Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int). This Intent will remain scheduled for redelivery until the service calls stopSelf(int) with the start ID provided to onStartCommand(Intent, int, int). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will will only be re-started if it is not finished processing all Intents sent to it (and any such pending events will be delivered at the point of restart).
I couldn't reproduce it on my device, but I can see multiple users crashing with the same error.
Any suggestions why this might be happening and how to fix it?
Related
I think im not clear at all, i do want the service to persist even if the main activity is destroyed via user action or android system does it, it does it well, but when the app is reopened at certain point i will want to check if a bg activity exists and stop it using a action button, THX in advance.
I launch a background service, in my MainActivity I can stop it and rerun it, the service persists when the app is closed from the running apps list, the problem is when I relaunch the closed app an try to stop the service with a button I have the app crashes cause it obviously tries to stop a service from which it no longer has a reference.
private void startBg(){
if (!hasPermissions() || mScanning) {
return;
}
clearLogs();
BgServiceIntent = new Intent(MainActivity.this, BgScanService.class);
startService(BgServiceIntent);
}
private void stopBg(){
stopService(BgServiceIntent);
}
Calling stopBg() after reopening the app fails, because BgServiceIntent no longer points to this service and thus I get this:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: mobile.link.imbera.apsys.imberalink, PID: 20104
java.lang.NullPointerException
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1568)
at android.app.ContextImpl.stopServiceCommon(ContextImpl.java:1628)
at android.app.ContextImpl.stopService(ContextImpl.java:1589)
at android.content.ContextWrapper.stopService(ContextWrapper.java:499)
at mobile.link.imbera.apsys.imberalink.MainActivity.stopBg(MainActivity.java:180)
at mobile.link.imbera.apsys.imberalink.MainActivity.lambda$onCreate$1$MainActivity(MainActivity.java:124)
at mobile.link.imbera.apsys.imberalink.MainActivity$$Lambda$1.onClick(Unknown Source)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
If the service already running in background then you need to call stopSelf() on same instance of that service .
Now as per service life Cycle onCreate() only call once in the lifetime of service .
WhereAs onStartCommand get called each time you call startService() with new intent. So what you can do is to pass a flag in intent to stop it .
Intent BgServiceIntent = new Intent(MainActivity.this, BgScanService.class);
BgServiceIntent.putExtra("close",true);
startService(BgServiceIntent);
And in Service .
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
boolean shouldClose=intent.getBooleanExtra("close",false);
if(shouldClose){
stopSelf();
} else {
// Continue to action here
}
return START_STICKY;
}
Maybe all you need to do is check to see if it's null before attempting to stop it:
private void stopBg(){
if(BgServiceIntent != null)
stopService(BgServiceIntent);
}
First of all start a service in START_NOT_STICKY.
Override this method in your Service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
and add this in your MainActivity.class
#override
private onDestroy() {
stopService(YourActiveService);
finishAffinity();
super.onDestroy()
}
I'm working on building a Location_Service for my Android App.I have a Service say , T_Service that starts on phone boot and checks for few conditions in its onStartCommand() to start my Location_Service. I want to send these conditions as an intent from a broadcast receiver associated to with the T_Service.
I do the following:
In the Broadcast Receiver
public class T_BroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context,T_Service.class);
i.putExtra("PARENT_ACTIVITY_NAME","com.example.helloworld");
context.startService(i);
}
}
In the T_Service class:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("APP","The intent has parent activity : "+intent.getExtras().getString("PARENT_ACTIVITY_NAME"));
}
I get a NullPointerException when my code reaches the above point that tries to print the value associated with the key that was set in the Intent.
Kindly advise me on how to go about the case of adding extras to an intent of a Service like T_Service that starts on phone boot.
The Stack trace for the Exception :
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start service org.abc.def.services.TService#41593b58 with null: java.lang.NullPointerException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2387)
at android.app.ActivityThread.access$1900(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1221)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at org.abc.def.services.TrackerService.onStartCommand(TrackerService.java:140)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2370)
at android.app.ActivityThread.access$1900(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1221)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
at dalvik.system.NativeStart.main(Native Method)
From the documentation (onStartCommand):
Parameter "intent": The Intent supplied to startService(Intent), as given.
This may be null if the service is being restarted after its process has gone
away, and it had previously returned anything except
START_STICKY_COMPATIBILITY.
If you're running this on phone boot is likely that you will get null on the intent because the process that started it has gone away.
To receive the the same intent you would need to return START_REDELIVER_INTENT in the onStartCommand method, as follows:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("APP","The intent has parent activity : "+intent.getExtras().getString("PARENT_ACTIVITY_NAME"));
return Service.START_REDELIVER_INTENT;
}
Returning START_REDELIVER_INTENT will make the intent parameter to be passed again to the onStartCommand method whenever the service get restarted (e.g on phone boot).
For more details check the documentation.
START_REDELIVER_INTENT
Constant to return from onStartCommand(Intent, int, int): if this
service's process is killed while it is started (after returning from
onStartCommand(Intent, int, int)), then it will be scheduled for a
restart and the last delivered Intent re-delivered to it again via
onStartCommand(Intent, int, int)
Please read the javadoc for onStartService. It says that the intent parameter can be null, so you should always check it for null before calling methods on it.
My experience is that even when you think that an IntentSevice will never receive a null there, it is actually still possible in extremely rare circumstances. So you should still check it for null even if you don't think it will happen.
replace this
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("APP","The intent has parent activity : "+intent.getExtras().getString("PARENT_ACTIVITY_NAME"));
}
with this
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Bundle b = getIntent().getExtras();
if (b != null){
Log.d("APP","The intent has parent activity :"+b.getString("PARENT_ACTIVITY_NAME")); }
Per the Intent API documentation, you must include a package name in the extra's name.
public Intent putExtra (String name, String value)
Added in API level 1
Add extended data to the intent. The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll".
Parameters
name The name of the extra data, with package prefix.
value The String data value.
Returns
Returns the same Intent object, for chaining multiple calls into a single statement.
See Also
putExtras(Intent)
removeExtra(String)
getStringExtra(String)
Please check your intent and extra string before accessing. May be it is null
if(intent.getExtras()!=null && intent.hasExtra("PARENT_ACTIVITY_NAME")){
Log.d("APP","The intent has parent activity : "+intent.getExtras().getString("PARENT_ACTIVITY_NAME"));
}
To pass an intent, please refer older thread.
Pass data from Activity to Service using an Intent
I am getting the following error on Android versions 4.1.2:
Fatal Exception: java.lang.RuntimeException: Unable to start receiver com.example.PluggedInBroadcastReceiver:
android.content.ReceiverCallNotAllowedException: IntentReceiver components are not allowed to register to receive intents
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2287)
at android.app.ActivityThread.access$1600(ActivityThread.java:143)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4961)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by android.content.ReceiverCallNotAllowedException: IntentReceiver components are not allowed to register to receive intents
at android.app.ReceiverRestrictedContext.registerReceiver(ContextImpl.java:152)
at android.app.ReceiverRestrictedContext.registerReceiver(ContextImpl.java:146)
at com.example.PluggedInBroadcastReceiver.getBatteryLevel(Unknown Source)
at com.example.PluggedInBroadcastReceiver.onReceive(Unknown Source)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2280)
at android.app.ActivityThread.access$1600(ActivityThread.java:143)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4961)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
at dalvik.system.NativeStart.main(NativeStart.java)
Here is the code that is causing the error. This receiver is being registered statically (in the AndroidManifest.xml) rather than dynamically:
public class PluggedInBroadcastReceiver extends WakefulBroadcastReceiver {
public static final String LOG_TAG = PluggedInBroadcastReceiver.class.getSimpleName();
private IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
String action = intent.getAction();
if (action != null && action.equals(Intent.ACTION_POWER_CONNECTED)) {
try {
Intent batteryStatusIntent = context.getApplicationContext().registerReceiver(null, iFilter);
double battPercentage = BatteryUtils.getBatteryLevel(batteryStatusIntent);
//Do something with the battery percentage value...
} catch (Exception e) {
Log.e(LOG_TAG, "Battery status intent was null");
}
}
}
}
}
I ran into this error in the past and found that my problems were being caused by the fact that the context that is passed to a Broadcast Receiver does not have the ability have registerReceiver() called on it.
I found some resources that suggest that you can convert the context passed to the Broadcast Receiver to an application context and then call registerReceiver() on the application context. This works for Android versions 4.2 and up, but fails on 4.1.2 (and possibly lower, but haven't tested explicitly). It seems like converting to the application context should allow registerReceiver() to be called, but that doesn't seem to work for all versions of Android.
Does anyone have an explanation for this behavior?
EDIT:
The plot thickens... I've now learned that this crash has occurred on android versions 4.1.1, 4.1.2, 4.3.0 and 5.1.1 over 93% of the crashes occurred on 4.1.2. I'm not sure we're going to find a solution for this, but my fix going forward is to never call registerReceiver() from a BroadcastReceiver. The behavior seems to be undefined and unpredictable even when using the application context which is apparently supposed to allow this.
This is my Service getting called on button click from an Activity. If I swipe my Activity left while Service is running it crashes. I have also tried running it in separate process by putting in android:process=":remote" in the manifest but it is still the same.
#Override
public void onCreate(){
super.onCreate();
Log.d("Service", "Creating");
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
#Override
public int onStartCommand (Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
Log.d("Started", "Service");
type = intent.getIntExtra("Type",-1);
mode = intent.getIntExtra("Mode",-1);
rank = intent.getIntExtra("Rank", -1);
latitude = intent.getDoubleExtra("Lat", -1.0);
longitude = intent.getDoubleExtra("Long", -1.0);
startTime = intent.getLongExtra("Start", 0);
endTime = intent.getLongExtra("End", 0);
The error I am getting is:
java.lang.RuntimeException: Unable to start service com.routofy.routofytest.MyLocationService#374afe93 with null: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Intent.getIntExtra(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2913)
at android.app.ActivityThread.access$2100(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Intent.getIntExtra(java.lang.String, int)' on a null object reference
at com.routofy.routofytest.MyLocationService.onStartCommand(MyLocationService.java:89)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2896)
at android.app.ActivityThread.access$2100(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
That is null pointer on type = intent.getIntExtra("Type",-1);
I understand that killing the app is killing the process and Intent this Service is getting is coming out to be null. But how to handle such cases that even if Activity is killed Intent is handed over to Service?
I want service to be totally independent of Activity. Also I am running it like:
Intent pickIntent = new Intent(getApplicationContext(),MyLocationService.class);
I understand that killing the app is killing the process and intent this service is getting is coming out to be null.
Since you haven't posted the return value of onStartCommand() I believe that it's START_STICKY meaning that the service is recreated by the system with null Intent passed in.
But how to handle such cases that even if activity is killed intent is handed over to service.
Just return START_REDELIVER_INTENT flag, which means that:
"If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand() with the last intent that was delivered to the service."
I need to listen screen_on and screenof_action.
I m using BroadcastReceiver with Service. But Im getting error. How can I fix my code?
this is my broadcastreceiver class :
public class BroadcastReceiver extends android.content.BroadcastReceiver {
public static boolean screenOff = true;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
// System.out.println("System ON OLDU ON ON ON ON ON ON");
Intent i = new Intent(context, MyNewService.class);
i.putExtra("screen_state", true);
context.startService(i);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
Intent i = new Intent(context, MyNewService.class);
i.putExtra("screen_state", false);
context.startService(i);
// System.out.println("System OFFFF OLDU OFFFF OFFFF OFFFF OFFFF");
}
}
}
this is my service class :
public class MyNewService extends Service {
BroadcastReceiver locker;
public static boolean screenOn = true;
public void onCreate(){
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
locker=new BroadcastReceiver();
registerReceiver(locker, filter);
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.i("START", "onStart");
screenOn = intent.getBooleanExtra("screen_state", false);
if(screenOn){
// startActivity(new Intent(this, MainActivity.class));
Log.i("SCREEN", "SCREEN OFFFFFFFFFFFFFFFF");
} else {
Log.i("SCREEN", "SCREEN OF FFFFFFFFFFFFFFFFFFFFFFFFF");
}
// If the screen is off then the device has been locked
}
#Override
public void onDestroy(){
unregisterReceiver(locker);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
this is my error code :
:19:52.696 32141-32141/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.codeexamples.app, PID: 32141
java.lang.RuntimeException: Unable to start service com.codeexamples.app.MyNewService#42672530 with Intent { cmp=com.codeexamples.app/.MyNewService }: java.lang.NullPointerException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2705)
at android.app.ActivityThread.access$2100(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.codeexamples.app.MyNewService.onStart(MyNewService.java:25)
at android.app.Service.onStartCommand(Service.java:450)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2688)
at android.app.ActivityThread.access$2100(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
this is my manifest permisson :
for service :
<service
android:name="com.codeexamples.app.MyNewService"
android:enabled="true" />
for broadcast :
<receiver android:name="com.codeexamples.app.BroadcastReceiver" >
</receiver>
for permission :
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
When I m checking error in the logcat shows me this line :
screenOn = intent.getBooleanExtra("screen_state", false);
Always show this line, I think something wrong in this line.
thanks for all, Finally I found solution :
this line :
boolean screenOn = intent.getBooleanExtra("screen_state", false);
must be work in the try/catch, finally I did like this, and its work completely
try {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
} catch
(Exception e) {}
Android might call your onStart() method without an intent. You can read more about this behavior in the Service Javadocs.
The best approach would be to override both onStart() and onStartCommand() methods (the former has been deprecated since API version 5) as described in the Javadocs, making sure that you cater for the case where the intent is null.
I tried you code and find a solution for you problem.
1.remove the following code from your manifest.xml
<receiver android:name="com.codeexamples.app.BroadcastReceiver" >
</receiver>
Since you registered your BroacastReceiver in your code, you should not register it in your menifest.xml. I have tried to register it in the menifest instead of code, but it can't work, don't know why.
2.Start you Service in your Activity initially to register your BroadcastReceiver, code as this:
private void startMyService() {
Intent intent = new Intent(this, MyNewService.class);
startService(intent);
}
Or you can move your code for registering your BroadcastReceiver to your Activity, thus you don't need to start your service initially.
3.Change your onStart() method to onStartCommand() method as this:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Here paste your code in your onStart() method.
return START_STICKY;
}
Update:
Notice this in the document(http://developer.android.com/reference/android/app/Service.html#START_STICKY):
Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.
So, If you did nothing wrong in your code, you should check the null intent yourself.