如何通过报警管理器传递构造函数?

How to pass constructors through Alarm Manager?

使用警报管理器调用 class 时,我收到错误消息:

"No method with zero constructors"

有没有办法通过 AlarmManager 传递构造函数或对象,或者我唯一的选择是只添加一个没有构造函数的方法吗?

(不使用Serializable方法)

编辑:

(被服务调用 class) 报警管理器代码:

public void startCollector(){
        final int LOOP_REQUEST_CODE = 4;
        Intent i = new Intent(getApplicationContext(),DataCollector.class);
        PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(),LOOP_REQUEST_CODE,i,0);
        long firstTime = SystemClock.elapsedRealtime();
        firstTime += 3*1000;
        Log.v("SPAM","Set");

        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 1000, sender);
    }

被叫class代码:

package com.project.backgroundprocesstest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class DataCollector extends BroadcastReceiver{
    LocationControl lc = null;
    public DataCollector(){

    }
    public DataCollector(Context context){
        lc = new LocationControl(context);
    }
    @Override
    public void onReceive(Context context,Intent intent){
        collectData(context);
    }
    private void collectData(Context context){
        HttpConnect conn = new HttpConnect();
        try {
            if (lc.getLocation() != null)
                Log.v("SPAM", lc.getLocation());
        }catch (NullPointerException e){

        }
        Log.v("SPAM", "SEND");
    }
}

目标:

我想每隔约 5 分钟从同一个 DataCollector 实例调用 collectData() 来收集数据并将其显示在通知中。

Is there a way to pass constructors or an object with AlarmManager

"pass constructors"的Java没有概念。

您使用 AlarmManagerPendingIntentPendingIntent 反过来与 ActivityServiceBroadcastReceiver 一起使用。所有这些都需要一个零参数 public 构造函数,因为 Android 框架知道如何使用它来创建那些 类.

的实例

is my only option just adding a method without constructors?

Java 中没有关于具有构造函数的方法的概念。

您使用 AlarmManagerPendingIntentPendingIntent 反过来与 ActivityServiceBroadcastReceiver 一起使用。您需要创建一个 ActivityServiceBroadcastReceiver 供您与 AlarmManager 一起使用,无需构造函数,但除此之外,使用您需要的那些组件中的任何一个的方法您选择使用(例如,onReceive() 表示 BroadcastReceiver)。

在您的代码示例中,您不妨将 lc = new LocationControl(context); 移动到 onReceive()。您的 DataCollector 将用于 一个 onReceive() 的调用,然后被丢弃,因此无论如何您每次都需要创建新的 LocationControl 对象。

I want to call collectData() from the same DataCollector instance every ~5 mins to collect data and show it in the notification

那不是 Android 的工作方式。让您的 DataCollector 将其数据保存在某处(数据库、SharedPreferences 或其他文件),并根据需要重新加载。如果你想对这些信息进行某种单例缓存,那很好,只要你小心避免内存泄漏。然而,它只是一个缓存;您的进程可以在 AlarmManager 个事件之间终止,因此您不能依赖在任何给定事件上填充的缓存。