Audiomanager android error null reference - android

I have a GPSCheck Service which produces alert sound when gps is turned off. I am getting null reference error. There's something wrong with the context.
Where am I going wrong?
public class GPSCheck extends BroadcastReceiver {
public Context context;
public Ringtone ringtone;
#Override
public void onReceive(Context context, Intent intent) {
LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
AlarmService obj = new AlarmService();
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
stopSiren();
}
else {
Toast.makeText(context, "Please switch on the GPS", Toast.LENGTH_LONG).show();
blowSiren();
}
}
public void blowSiren() {
AudioManager audioManager = (AudioManager) this.context.getSystemService("audio");
audioManager.setStreamVolume(4, audioManager.getStreamMaxVolume(4), 0);
Uri path = Uri.parse("android.resource://" + this.context.getPackageName() + "/raw/alert");
RingtoneManager.setActualDefaultRingtoneUri(this.context, 4, path);
this.ringtone = RingtoneManager.getRingtone(this.context, path);
this.ringtone.setStreamType(4);
this.ringtone.play();
}
public void stopSiren() {
AudioManager audioManager = (AudioManager) this.context.getSystemService("audio");
audioManager.setStreamVolume(4, audioManager.getStreamMaxVolume(4), 0);
Uri path = Uri.parse("android.resource://" + this.context.getPackageName() + "/raw/alert");
RingtoneManager.setActualDefaultRingtoneUri(this.context, 4, path);
this.ringtone = RingtoneManager.getRingtone(this.context, path);
this.ringtone.setStreamType(4);
this.ringtone.stop();
}
}
This is the error I m geting : -
11-18 21:26:36.784 1411-1411/com.track.client E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.track.client, PID: 1411
java.lang.RuntimeException: Unable to start receiver com.pasupatigroup.client.GPSCheck: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2789)
at android.app.ActivityThread.access$1800(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1468)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at com.track.client.GPSCheck.blowSiren(GPSCheck.java:35)
at com.track.client.GPSCheck.onReceive(GPSCheck.java:30)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2782)
at android.app.ActivityThread.access$1800(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1468) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:234) 
at android.app.ActivityThread.main(ActivityThread.java:5526) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

First. I don't know if this is your problem but you should get AudioManager by calling using the constant Context.AUDIO_SERVICE, not rolling your own strings.
Second. Don't store the context, send it in via input parameter to blow and stop siren. Otherwise you might get freaky leaks (yep, you can leak memory in Java).
Dunno if this will fix your problem, but that's what I noticed right off anyway.

Probably your this.context.getSystemService("audio"); call fails because the this.context is null.
You probably meant to set it to the class member in onReceive(Context context, Intent intent):
this.context = context;
But like the other answer points out it's instead better to pass it to stopSiren() and blowSiren() when calling those methods.
That's covered in the BroadcastReceiver documentation:
A BroadcastReceiver object is only valid for the duration of the call
to onReceive(Context, Intent). Once your code returns from this
function, the system considers the object to be finished and no longer
active.

Related

Calling/Attaching MainAcitivty method to click of notification button

Have been creating a custom notification, so far implemented it successfully getting the notification, however when i am trying to call a function/method from MainActivity using the button on the notification i created i get the below error :
System services not available to Activities before onCreate()
Below is the method defined by me inside the MainActivity that updates the notification UI and also stops the mediaplayer.
public void attachMediaActivity()
{
//INITIALIZE THE CONTEXT
context =this;
notificationManager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
remoteViews=new RemoteViews(this.getPackageName(),R.layout.custom_notification);
remoteViews.setImageViewResource(R.id.notif_icon,R.drawable.stream_icon);
remoteViews.setTextViewText(R.id.notif_title,"stopped");
Intent button_intent= new Intent("button_clicked");
button_intent.putExtra("id",notification_id);
Intent notification_intent=new Intent(context,MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(context,0,notification_intent,PendingIntent.FLAG_UPDATE_CURRENT);
builder =new NotificationCompat.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setCustomBigContentView(remoteViews)
.setContentIntent(pendingIntent)
.setOngoing(true);
notificationManager.notify(notification_id,builder.build());
if (mediaPlayer.isPlaying())
{
mediaPlayer.stop();
}
}
Broadcast listener attached to the button of notification that calls the above method from main activity.
public class Button_listener extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent)
{
NotificationManager manager =(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(intent.getExtras().getInt("id"));
Toast.makeText(context, "GENERATED BY NOTIFICATION", Toast.LENGTH_SHORT).show();
new MainActivity().attachMediaActivity();
}
}
LOGCAT:
01-24 11:52:29.010 13062-13062/com.amplitude.tron.samplemediaplayer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amplitude.tron.samplemediaplayer, PID: 13062
java.lang.RuntimeException: Unable to start receiver com.amplitude.tron.samplemediaplayer.Button_listener: java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2750)
at android.app.ActivityThread.access$1800(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1433)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5525)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.Activity.getSystemService(Activity.java:5288)
at com.amplitude.tron.samplemediaplayer.MainActivity.attachMediaActivity(MainActivity.java:159)
at com.amplitude.tron.samplemediaplayer.Button_listener.onReceive(Button_listener.java:21)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2743)
at android.app.ActivityThread.access$1800(ActivityThread.java:157) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1433) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5525) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620) 
What i have implemeted so far :
where am i going wrong .. also prior to calling notification manager i have been getting getPackageName() as NULL
Please help! Thanks in advance
new MainActivity().attachMediaActivity();
Problem lies here. Contrary of normal way, creating an instance of Activity with a new tag won't let you go through with its lifecycle that it supposed to.
You can launch your Activity by setting up a bundle, pass it with Intent, initiate a startActivity and finally check the bundle value in Activity and invoke the attachMediaActivity method. Or else, if you want, you can get a hold of your current Activity instance in these ways and call the method.
The error that you got clearly says, System services not available to Activities before onCreate().
That is, You can not use NotificationManager from an Activity without calling startActivity(Intent).
What you can do is, start the activity with intent+ extras to call the method inside the MainActivity. OR you can use the CallBack method using Interfaces.
Update
Declare Intent as:
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("attachMedia",true); // Extra info
context.startActivity(intent);
And now, inside the MainActivity onCreate(), (after all initialization)
boolean attachMedia = getIntent().getBooleanExtra("attachMedia",false);
if (attachMedia) {
attachMediaActivity();
}

App crashes when closed while using a service android, as im trying to use intents

public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getExtras() != null) {
String temp = intent.getStringExtra("key");
temp1 = Integer.parseInt(temp);
counter = temp1;
}
}
I'm passing data to the service and it works perfectly when the app is open but crashes as soon as i close the app.. I've tried a lot of things and I'm new to android. Any help would be appreciated
Thanks in advance.
Here is the log
03-21 15:35:07.868 21818-21818/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cs442.shash5259.assignment_6, PID: 21818
java.lang.RuntimeException: Unable to start service com.cs442.shash5259.assignment_6.Myservice#9d88461 with null: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap17(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1452)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at com.cs442.shash5259.assignment_6.Myservice.onStartCommand(Myservice.java:55)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3028)
at android.app.ActivityThread.-wrap17(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1452) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5443) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 
Looking at the logs, it is clear that your Intent object in onStartCommand is null, when app is closed.
Looking at the documentation inside the source code of Service, it is mentioned that:
The Intent supplied to onStartCommand 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.
You can deal with this in at least 2 different ways depending on your app's requirement.
1.You can modify the code as below in your onStartCommand:
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent!= null) {
String temp = intent.getStringExtra("key");
temp1 = Integer.parseInt(temp);
counter = temp1;
}
}
This will prevent the crash but will not update the counter
2.Or you may return START_REDELIVER_INTENT in the onStartCommand() callback in service so that the entire intent is sent following a restart, thus preventing Intent from being null.

Getting error while stopping foreground service in watch from mobile

From my mobile I am starting a foreground service in my android watch. I am able to do that correctly. But when I try to stop the service as well as the activity in watch , I am getting an error message( watch app is crashing). I am using message listener service to receive the message from mobile.
I also have a stop button in watch app which is running perfectly(if I try to stop the service from watch itself) and it has the same lines of code. I am not sure where I am wrong when I receive message from mobile app to stop the foreground service.
#Override public void onMessageReceived(MessageEvent messageEvent) {
Log.i(INFOTAG, "Stop msg received");
if(messageEvent.getPath().equals(STOP_MESSAGE_PATH_2)){
started = false;
Intent stopIntent = new Intent(
MainActivity.this, ForegroundService.class);
stopService(stopIntent);
this.finish();
}
}
Below is the error log I am getting:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
at android.content.ComponentName.(ComponentName.java:77)
at android.content.Intent.(Intent.java:4160)
at com.magi.magidemo.MainActivity.onMessageReceived(MainActivity.java:464)
at com.google.android.gms.wearable.internal.zzcf$5.zza(Unknown Source)
at com.google.android.gms.wearable.internal.zzcf$5.zzs(Unknown Source)
at com.google.android.gms.internal.zzmn.zzb(Unknown Source)
at com.google.android.gms.internal.zzmn$zza.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
You need to get the Activity's instance from the override method.
Like this:
public MainActivity activity;
// in the override method
this.activity = activity;
Then use it:
Intent stopIntent = new Intent(
activity, ForegroundService.class);
Have a look: android.content.Context.getPackageName()' on a null object reference

Android service with START_STICKY crashes on killing app

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."

Intent always null onStartCommand

I have following code
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null) {
Log.i("INTENT", intent.getAction().toString());
}
return START_STICKY;
}
but it always returns NullPointerException on line:
Log.i("INTENT", intent.getAction().toString());
Why? I'm checking above if "intent" variable is not null. If that's the case execute following code. But i still got nullpointerexception.
Service is started from activity like that:
startService(new Intent(this, MainService.class));
What am I doing wrong?
You are getting a NullPointerException because intent.getAction() seems to return null.
You should extend your check to this:
if(intent != null && intent.getAction() != null) {
If you want to add an Action to your intent you need to call setAction():
Intent i = new Intent(this, MainService.class);
i.setAction("foo");
startService(i);
I got the similar stack,add the check
intent.getAction() != null
it worked.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.languoguang.welcomeapp, PID: 17676
java.lang.RuntimeException: Unable to start service com.example.languoguang.welcomeapp.CountService#f6049d4 with Intent { cmp=com.example.languoguang.welcomeapp/.CountService }: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3698)
at android.app.ActivityThread.access$1500(ActivityThread.java:198)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1668)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.example.languoguang.welcomeapp.CountService.onStartCommand(CountService.java:24)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3679)
at android.app.ActivityThread.access$1500(ActivityThread.java:198) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1668) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6649) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826) 
I/Process: Sending signal. PID: 17676 SIG: 9

Categories

Resources