当用户点击通知时如何启动活动?

19

我试图将我在教程中找到的一些代码转换为自己的用途。最初,当用户单击由我的应用程序生成的通知时,该代码启动了系统联系人列表。我尝试启动自己的Activity而不是启动联系人列表,但它没有起作用。更具体地说,什么都没有发生。没有错误,我的Activity也没有加载。单击后,通知窗口消失,并且原始的Activity仍然可见。

这是我的代码:

public class MyBroadcastReceiver extends BroadcastReceiver {
    private NotificationManager mNotificationManager;
    private int SIMPLE_NOTFICATION_ID;

    public void onReceive(Context context, Intent intent){
        Bundle extras = intent.getExtras();

        String deal = (String) extras.get("Deal");
        String title = "Deal found at " + (String) extras.get("LocationName");

        mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notifyDetails = new Notification(R.drawable.icon, title,System.currentTimeMillis());

        Class ourClass;
        try {
            ourClass = Class.forName("com.kjdv.gpsVegas.ViewTarget");
            Intent startMyActivity = new Intent(context, ourClass);

            PendingIntent myIntent = PendingIntent.getActivity(context, 0,startMyActivity, 0);
            notifyDetails.setLatestEventInfo(context, title, deal, myIntent);
            notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
            notifyDetails.flags |= Notification.DEFAULT_SOUND;
            mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

这是我在AndroidManifest.xml文件中的条目...

  <activity android:name=".ViewTarget" android:label="@string/app_name" >
        <intent-filter>
            <action android:name="com.kjdv.gpsVegas.ViewTarget" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
   </activity>

这是我希望启动的Activity...

public class ViewTarget extends ListActivity {
    public ListAdapter getListAdapter() {
        return super.getListAdapter();
    }

    public ListView getListView() {
        return super.getListView();
    }

    public void setListAdapter(ListAdapter adapter) {
        super.setListAdapter(adapter);
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.locations);
        Log.v("db", "Inside ViewTarget");
    }
}

1
我找到了问题所在。我在清单文件中的活动声明中省略了包名。我将 <activity android:name=".ViewTarget" android:label="@string/app_name" > 更改为 <activity android:name="com.kjdv.gpsVegas.ViewTarget" android:label="@string/app_name" />。现在一切都正常了。谢谢! - Kevin
6个回答

26

您正在运行哪个Android版本?您可能想尝试使用NotificationCompat。这个类包含在最新的支持包中。

Intent notificationIntent = new Intent(context, ViewTarget.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,
                0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

NotificationManager nm = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = context.getResources();
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentIntent(contentIntent)
       .setSmallIcon(R.drawable.app_icon)
       .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.app_icon))
       .setTicker(payload)
       .setWhen(System.currentTimeMillis())
       .setAutoCancel(true)
       .setContentTitle("Message")
       .setContentText(payload);
Notification n = builder.getNotification();

n.defaults |= Notification.DEFAULT_ALL;
nm.notify(0, n);

编辑: 我知道这是一个旧的帖子/问题,但是这个答案帮助我展示了在点击通知时的活动。 对于那些这不起作用的人,可能是因为您没有在清单中“注册”活动。例如:

<activity
   android:name="com.package.name.NameOfActivityToLaunch"
   android:label="Title of Activity" >
   <intent-filter>
     <action android:name="com.package.name.NAMEOFACTIVITYTOLAUNCH" />

     <category android:name="android.intent.category.DEFAULT" />
   </intent-filter>
</activity>

希望能够成功。 希望对你有所帮助...


1
我做错了什么吗?我把代码粘贴进去,Eclipse无法解析NotificationCompat,也没有提供导入建议。这个命名空间是从哪里来的?谢谢。 - Kevin
我添加了代码。但是它没有加载活动。通知触发,但单击它时什么也不会发生。通知消失后,默认屏幕仍然可见。有什么想法吗? - Kevin
好的,我会添加一个新的活动。它可以只是一个扩展ACTIVITY的空活动吗?还是我应该添加UI元素? - Kevin
请查看所做的编辑,希望它能够起作用并帮助其他人。对于那些无法工作的人来说,可能是因为您没有在清单中“注册”该活动。例如:`<activity android:name="com.package.name.NameOfActivityToLaunch" android:label="Title of Activity" > <intent-filter> <action android:name="com.package.name.NAMEOFACTIVITYTOLAUNCH" /> </intent-filter> </activity>` - user959631
感谢您的帮助 :) - Vivek Singh
显示剩余4条评论

5

您应该为Intent设置操作和类别。

Intent startMyActivity = new Intent(context, ourClass);
startMyActivity .setAction(Intent.ACTION_MAIN);
startMyActivity .addCategory(Intent.CATEGORY_LAUNCHER);

它工作了


4
我可以帮您进行翻译。这篇文章是关于编程的,作者解决了一个问题:在清单文件中的活动声明中忘记包含包名。下面是错误的示例:
activity android:name=".ViewTarget" android:label="@string/app_name" 

正确:

activity android:name="com.kjdv.gpsVegas.ViewTarget" android:label="@string/app_name" 

1

你可以尝试移除Intent过滤器,让它看起来像这样:

<activity android:name=".ViewTarget" android:label="@string/app_name" />

另外,不确定这段代码是否有效:

ourClass = Class.forName("com.kjdv.gpsVegas.ViewTarget"); Intent startMyActivity = new Intent(context, ourClass);

你可以尝试改成这样:

Intent startMyActivity = new Intent(context, ViewTarget.class);


我移除了意图过滤器,并将我的意图初始化代码替换为你的代码。但仍然没有反应 :( 点击通知后仍停留在默认/主活动页面。 - Kevin
ViewTarget Activity是否已经在运行(是您的默认/主要活动吗?) - theelfismike
不,它没有运行。有一个单独的活动是主要活动。 - Kevin
改成(int) System.currentTimeMillis(),但仍然没有反应 :( 点击通知只是关闭了通知滑动窗口,显示我的默认表单。我希望我能在调试方面提供更多帮助,但我还在学习Java和Android系统。有什么我可以添加来帮助测试和找到罪魁祸首吗?空值检查? - Kevin
以下是两行相关的输出:
  1. 04-17 23:47:11.047: I/ActivityManager(82): 开始活动:Intent { flg=0x10000000 cmp=kjdv.gpsVegas/com.kjdv.gpsVegas.ViewTarget bnds=[0,387][480,483] }
  2. 04-17 23:47:11.417: W/InputManagerService(82): 窗口已经聚焦,忽略焦点收集:com.android.internal.view.IInputMethodClient$Stub$Proxy@44b57030
- Kevin
显示剩余5条评论

1

请检查这段代码

            public class TestActivity extends Activity {
private static final int UNIQUE_ID = 882;

public static NotificationManager nm;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Intent navigationIntent = new Intent();


    navigationIntent.setClass(classname.this, MainActivity.class);


    PendingIntent pi = PendingIntent.getActivity(this, 0, navigationIntent,
            0);

    String body = "New notificattion added!!!";
    String title = "Notification";


    Notification n = new Notification(R.drawable.icon, body,
            System.currentTimeMillis());

            //this is for giving number on the notification icon

    n.number = Integer.parseInt(responseText);

    n.setLatestEventInfo(this, title, body, pi);
    n.defaults = Notification.DEFAULT_ALL;

    nm.notify(UNIQUE_ID, n);

嗯... 这个不起作用。 我把 nm.notify 改成了 n.notify(假设这是打字错误)。然后,Eclipse 从 API 中删除了我的 Notify() 方法调用中的参数。有没有一个带参数的 Notification.Nofity 版本? - Kevin
抱歉回复晚了...我正在编辑我的代码。nm是通知管理器的实例。 - Jackson Chengalai

1
为了从一个Intent启动一个Activity,你需要添加一个标志:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

即使您在Intent的构造函数中声明类,这也是正确的。

我添加了这个。不幸的是,没有任何改变。该活动无法加载。只停留在默认/主要活动屏幕上。 - Kevin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接