簡體   English   中英

什么是傳遞給BroadcastReceiver的onReceive()的Context?

[英]What is the Context passed into onReceive() of a BroadcastReceiver?

BroadcastReciveronReceive方法中傳遞的上下文是什么:

public void onReceive (Context context, Intent intent)

根據官方文件

接收器運行的上下文。

一點點研究給出了以下結果......

對於靜態接收器

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("PANKAJ", "Context class " + context.getClass().getName());
        Log.e("PANKAJ", "Application Context class "
                + context.getApplicationContext().getClass().getName());
    }
}

我得到了以下日志

08-05 06:51:33.448: E/PANKAJ(2510): Context class android.app.ReceiverRestrictedContext
08-05 06:51:33.448: E/PANKAJ(2510): Application Context class android.app.Application

對於bynamic接收器(注冊成活動MainActivity)之類的

private BroadcastReceiver myReceiver = new BroadcastReceiver() {
    public void onReceive(android.content.Context context, Intent intent) {
        Log.e("PANKAJ", "Context class " + context.getClass().getName());
        Log.e("PANKAJ", "Activity Context class "
            + MainActivity.this.getClass().getName());
        Log.e("PANKAJ", "Application Context class "
            + context.getApplicationContext().getClass().getName());
    }
};

我得到了以下日志

08-05 06:53:33.048: E/PANKAJ(2642): Context class com.example.testapp.MainActivity
08-05 06:53:33.048: E/PANKAJ(2642): Activity Context class com.example.testapp.MainActivity
08-05 06:53:33.048: E/PANKAJ(2642): Application Context class android.app.Application

因此,當文檔中的語句表明接收器正在運行的上下文時

這是一個應用程序上下文。 與方法相同的一個

getApplicationContext()

但:

此實例是ReceiverRestrictedContext,禁用了兩個主要功能; 調用registerReceiver()和bindService()。 現有的BroadcastReceiver.onReceive()中不允許這兩個函數。 每次接收者處理廣播時,傳遞給它的上下文都是一個新實例。

使用getApplicationContext()將上下文發送到onReceive方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM