Android notification from service does not open ac

2019-02-26 16:40发布

问题:

Updated MyService @CommonsWare

i have a service that if started will set up an alarm that triggers the notification.

This works fine and the alarms are canceled if the service is stopped.

i am trying to get the notification to open a new activity class but can not get it done

my service class is the following:

   package com.example.andtip;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;


public class BReceiver extends BroadcastReceiver {
private static final int MY_NOTIFICATION_ID=1;
   NotificationManager notificationManager;
   Notification myNotification;   

public void onReceive(Context context, Intent intent) {

    Intent myIntent = new Intent(context, DoSomething.class);

    PendingIntent pi = PendingIntent.getBroadcast(context, 0,  new Intent("com.example.andtip"),0 );
    PendingIntent pi2 = PendingIntent.getActivity(context, 0,  myIntent,0 );

        myNotification=new NotificationCompat.Builder(context)
     .setContentTitle("This is a notification from the example alarm application.")
        .setContentText("Notification")      
        .setTicker("Notification!")
        .setWhen(System.currentTimeMillis())
     .setContentIntent(pi)
        .setDefaults(Notification.DEFAULT_SOUND)                
        .setAutoCancel(true)
        .setSmallIcon(R.drawable.ic_launcher)
     .build();

        notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
     notificationManager.notify(MY_NOTIFICATION_ID, myNotification);

      }
}

how should i link the intent pi2 to the notification?

回答1:

i am trying to get the notification to open a new activity class but can not get it done

You are using getBroadcast() to create your PendingIntent. Use getActivity() to create a PendingIntent that starts up an activity. Make sure that the Intent you put in the PendingIntent is for an activity, and make sure that the activity has its entry in the manifest.