来自服务的 Android 通知未打开 Activity

标签 android android-activity service notifications launch

更新了 MyService @CommonsWare

我有一项服务,如果启动该服务,将设置一个触发通知的警报。

这工作正常,如果服务停止,警报就会取消。

我正在尝试获取打开新 Activity 类的通知,但无法完成

我的服务类别如下:

   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);

      }
}

我应该如何将 Intent pi2 链接到通知?

最佳答案

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

您正在使用 getBroadcast() 创建 PendingIntent。使用 getActivity() 创建启动 Activity 的 PendingIntent。确保您放入 PendingIntent 中的 Intent 是针对某个 Activity 的,并确保该 Activity 在 list 中具有其条目。

关于来自服务的 Android 通知未打开 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26414744/

相关文章:

android - 如何使用 DialogFragment 和 FragmentManager 制作 DatePicker?

Android eclipse错误: Unknown option '--auto-add-overlay'

android - 强制关闭尝试使用默认构造函数

android - 从 "Choose Application"列表中隐藏 NFC 应用程序/通过外部 NFC Intent 禁用启动

Android:从 SurfaceView 更改 Activity

java - 类 Activity 扩展了 ActionBarActivity 已弃用

service - Consul:在不知道现有成员IP的情况下加入

java - 媒体应用程序缓冲时间太长

java - 在 OnCreate() 方法中绑定(bind)服务时出现 NullPointerException

android - AsyncTask 已弃用?使用什么方法代替 onPreExecute 和 onPostExecute?