简体   繁体   English

Android BroadcastReceiver nullpointerexception在注册

[英]Android BroadcastReceiver nullpointerexception on registering

I'm Trying to receive a download completed action but it says the broadcast receiver is null on registering. 我正在尝试接收下载完成的操作,但是它说广播接收器在注册时为空。
But I checked it and it clearly isn't. 但是我检查了一下,显然不是。

LogCat错误

public class UpdateHandler extends Activity{

    private DownloadManager manager;

    /**
     * Class Constructor will only be used for non-static Referencing in a static condition.
     */
    public UpdateHandler(DownloadManager dm){
        this.manager = dm;  
    }


    public void updateApp(final String appname) {

        String apkurl = apk_url + appname;
        DownloadManager.Request request = new DownloadManager.Request(
                Uri.parse(apkurl));
        request.setDescription("Even geduld aub...");
        request.setTitle("Bimii-app wordt gedownload");
        request.setDestinationInExternalPublicDir(
                Environment.DIRECTORY_DOWNLOADS, appname);

        File folder1 = android.os.Environment
                .getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS
                        + "/" + appname);
        if (folder1.exists()) {
            Log.d("!--->", Environment.DIRECTORY_DOWNLOADS + "/" + appname
                    + " pre-existant, delete!");
            folder1.delete();
        } else {
            Log.d("!--->", Environment.DIRECTORY_DOWNLOADS + "/" + appname
                    + " is new.");
        }

        registerBroadcastReceiver(request, appname);
    }


    /**
     * Installing a specific Application by name.
     * @param appname
     */
    private void installUpdates(String appname) {
        Log.d("installing ", appname);
        File filepath = android.os.Environment
                .getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS
                        + "/" + appname);

        Intent install_intent = new Intent(Intent.ACTION_VIEW);
        install_intent.setDataAndType(Uri.fromFile(filepath),
                "application/vnd.android.package-archive");
        install_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);     
        startActivity(install_intent);
    }


    private void registerBroadcastReceiver(DownloadManager.Request request, final String appname){
        // get download service and enqueue file
        manager.enqueue(request);

        BroadcastReceiver downloadDone = new BroadcastReceiver() {
            public void onReceive(Context ctxt, Intent intent) {
                Log.d("!--->", "File Download Completed + appname");
                installUpdates(appname);
            }
        };

        registerReceiver(downloadDone, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
}

And this is how I initialize my UpdateHandler as requested. 这就是我按要求初始化UpdateHandler的方式。 This happens in my home activity. 这发生在我的家庭活动中。

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Initialization
    init();

    loadApps();
    update_handler = new UpdateHandler((DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE));
    setupButtons();
    loadListView();
}

The android version I'm running is 4.2.2 in case that matters. 我正在运行的android版本是4.2.2,以防万一。

You need to have an activity/Application context for registering the broadcast receiver. 您需要具有活动/应用程序上下文才能注册广播接收器。

As I can see from screenshot, you are registering receiver from utils.UpdateHandler file so you need to pass application context to this method. 从屏幕截图中可以看到,您正在从utils.UpdateHandler文件中注册接收者,因此您需要将应用程序上下文传递给此方法。

So code will be 所以代码将是

/**
     * Class Constructor will only be used for non-static Referencing in a static condition.
     */
    public UpdateHandler(Context context, DownloadManager dm){
        this.mContext = context;
        this.manager = dm;  
    }

and then call context.registerReceiver() 然后调用context.registerReceiver()

In your UpdateHandler class the context is not initialized yet. 在您的UpdateHandler类中, context尚未初始化。 Because you are just extending the Activity class. 因为您只是扩展Activity类。 Without calling the Activity's lifecycle method (eg: onCreate ) the context will not be available to you. 如果不调用Activity's生命周期方法(例如: onCreate ),则上下文将对您不可用。 It will be null. 它将为空。

So I suggest you pass the context from your HomeActivity to the UpdateHandler class through the constructor and use that context to register the receiver. 因此,我建议您通过构造函数将上下文从HomeActivityUpdateHandler类,并使用该上下文注册接收者。

change your UpdateHandler like this 像这样更改您的UpdateHandler

public class UpdateHandler{
    private DownloadManager manager;
    private Context mContext
    public UpdateHandler(Context mContext,DownloadManager dm){
        this.manager = dm;  
        this.mContext = mContext;
    }

and to register your receiver use this 并注册您的接收器使用此

context.registerReceiver(downloadDone, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE));

Also you dont want to extend UpdateHandler class with Activity 你也不想用Activity扩展UpdateHandler类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM