0

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 : NOTIFICATION SNAPSHOT

where am i going wrong .. also prior to calling notification manager i have been getting getPackageName() as NULL Please help! Thanks in advance

IteratioN7T
  • 363
  • 8
  • 21

2 Answers2

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

Community
  • 1
  • 1
fluffyBatman
  • 6,524
  • 3
  • 24
  • 25
  • hi i have never used intents .. although i may be this make sense ? intent = new Intent(context, MainActivity.class); then where to next !? the context and intent is the onReceive parameters! – IteratioN7T Jan 24 '17 at 07:13
  • Head over to this https://developer.android.com/training/basics/firstapp/starting-activity.html and go through the content. You'll get the idea on how to begin an Activity through Intent with bundle. – fluffyBatman Jan 24 '17 at 07:20
  • Hi fluffyBatman i have managed to get the notification working however i have a problem on the notification button click, the activity get recreated on top of the old activity! and if i try to change the launchmode to single the above UI changes doesnt happen, please help – IteratioN7T Jan 24 '17 at 11:11
0

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();
}
Nizam
  • 5,698
  • 9
  • 45
  • 57
  • Hi Nizam this is what i have done so far : intent = new Intent(context, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); – IteratioN7T Jan 24 '17 at 07:27
  • How do i make a call to Main Activity function ?? PS : i am new to INTENTS – IteratioN7T Jan 24 '17 at 07:27
  • 2
    addExtra is not recognized ! – IteratioN7T Jan 24 '17 at 08:45
  • Sorry, Typo. Use putExtra() – Nizam Jan 24 '17 at 08:50
  • Hi Nizam its working however it is creating a new notification instead of updating the old one also given that i am using the same notification id, any thoughts on that ? – IteratioN7T Jan 24 '17 at 09:02
  • From where, you are triggering the first notification? Is it Ongoing(true)? – Nizam Jan 24 '17 at 09:12
  • Yes ongoing is true... i am creating the notification using onClickListener of button in the main activity – IteratioN7T Jan 24 '17 at 09:16
  • Hi nizam i kind of got it working but, there is two activity getting created when i click on notif button, and when i change the launch mode to single then the above ui changes dont work... please help – IteratioN7T Jan 24 '17 at 11:13