Kevik
Kevik

Reputation: 9361

How to launch activity from click on notification?

How do I launch an activity when the user clicks on the notification? I am having constant crashes. I can not get the click on the notification to work. There is an onclick method shown below. When a button called ButtonOne is pressed, it will launch a notification in the top menu bar of the screen. I wanted to user to be able to press the notification and have it launch the activity called MainActivity. It crashes and will not launch the page. There is probably something wrong in my code for notification that I put inside of the MainActivity class. What is wrong?

    ButtonOne.setOnClickListener(new View.OnClickListener() {

      private int mId;

    // anonymous inner class override for on click
    public void onClick(View v) {

        Intent myIntent = new Intent(MainActivity.this, CoverFlowExample.class);
         MainActivity.this.startActivity(myIntent);



         NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(MainActivity.this)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle("My notification")
                    .setContentText("Hello World!");
            // Creates an explicit intent for an Activity in your app
            Intent resultIntent = new Intent(MainActivity.this, MainActivity.class);

            // The stack builder object will contain an artificial back stack for the
            // started Activity.
            // This ensures that navigating backward from the Activity leads out of
            // your application to the Home screen.
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainActivity.this);
            // Adds the back stack for the Intent (but not the Intent itself)
            stackBuilder.addParentStack(MainActivity.class);
            // Adds the Intent that starts the Activity to the top of the stack
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent =
                    stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                    );
            mBuilder.setContentIntent(resultPendingIntent);
            NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // mId allows you to update the notification later on.
            mNotificationManager.notify(mId, mBuilder.build());


    }
});

Upvotes: 2

Views: 3497

Answers (1)

Kevik
Kevik

Reputation: 9361

Found out that the problem was the AVD android emulator not the code. For some reason it did not update the code from earlier version. Tested it again and now it runs with no errors.

Upvotes: 2

Related Questions