Intent结构之间有什么区别

时间:2018-06-03 18:05:57

标签: android android-intent

我想知道这些实施之间的区别是什么:

首先:

calendar = Calendar.getInstance();
intent = new Intent("myservice.MyReceiver");
pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 
PendingIntent.FLAG_UPDATE_CURRENT);
am = (AlarmManager)this.getSystemService(ALARM_SERVICE);

am.cancel(pendingIntent);

第二

calendar = Calendar.getInstance();
intent = new Intent(this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am = (AlarmManager)this.getSystemService(ALARM_SERVICE);

am.cancel(pendingIntent);

他们两个都在工作并做同样的事情。我不明白第一种方法如何知道什么是推荐上下文,我不需要像第二种方法那样具体化上下文

2 个答案:

答案 0 :(得分:3)

new Intent("myservice.MyReceiver")是一个隐含的Intent。它没有定义要与之交谈的特定接收器。任何符合条件且已注册以侦听具有该操作字符串的Intent的接收者都将作出响应。通常,出于安全原因,避免了这种方法。此外,在Android 8.0 +上的清单中注册的接收者无法接收隐式广播。

new Intent(this, MyReceiver.class)是明确的Intent。它标识了应该响应广播的特定应用程序(通过Context获取应用程序ID)和类(通过Java .class对象)。

答案 1 :(得分:0)

如果您只是在两个构造函数上按ctrl + B(转到声明)或ctrl + Q(请参阅文档),您将得到答案。

/**
 * Create an intent with a given action.  All other fields (data, type,
 * class) are null.  Note that the action <em>must</em> be in a
 * namespace because Intents are used globally in the system -- for
 * example the system VIEW action is android.intent.action.VIEW; an
 * application's custom action would be something like
 * com.google.app.myapp.CUSTOM_ACTION.
 *
 * @param action The Intent action, such as ACTION_VIEW.
 */
public Intent(String action) {
    setAction(action);
}

/**
 * Create an intent for a specific component.  All other fields (action, data,
 * type, class) are null, though they can be modified later with explicit
 * calls.  This provides a convenient way to create an intent that is
 * intended to execute a hard-coded class name, rather than relying on the
 * system to find an appropriate class for you; see {@link #setComponent}
 * for more information on the repercussions of this.
 *
 * @param packageContext A Context of the application package implementing
 * this class.
 * @param cls The component class that is to be used for the intent.
 *
 * @see #setClass
 * @see #setComponent
 * @see #Intent(String, android.net.Uri , Context, Class)
 */
public Intent(Context packageContext, Class<?> cls) {
    mComponent = new ComponentName(packageContext, cls);
}