为广播接收器提供上下文

时间:2015-12-29 21:51:52

标签: android broadcastreceiver

我正在开发一个简单的警报应用程序,即使应用程序未启动也会通知用户。我有点过头了,很抱歉,如果我看起来像是一个Java菜鸟。

以下是本教程:http://www.compiletimeerror.com/2013/10/alarm-example-in-android.html?m=1 它没有提供太多解释,但它简化了很多事情。

我的问题是为broadcastreceiver类提供上下文。我知道还有其他问题要求如何做到这一点,我已经读完了它们。我的问题是,我不知道如何在构造函数中明确地传递上下文,因为我在活动类中使用广播接收器。

这就是我的意思。这是单击按钮时将运行的代码。我还没有完成它,所以它只是一个骨架atm。

Option Explicit
Public installer, fullmsg, comp, prod, a, fso, pname, ploc, pid, psorce, pcache, pver

Set fso = CreateObject("Scripting.FileSystemObject")
Set a = fso.CreateTextFile("prods.txt", True)

' Connect to Windows Installer object
Set installer = CreateObject("WindowsInstaller.Installer")
a.writeline ("Products")
on error resume next
For Each prod In installer.products
   pid = installer.productinfo (prod, "ProductID")
   pname = installer.productinfo (prod, "ProductName")
   pver = installer.productinfo (prod, "VersionString")
   psorce=installer.productinfo(prod, "InstallSource")
   ploc = installer.productinfo (prod, "InstallLocation")  
 pcache = installer.productinfo(prod, "LocalPackage") 
   a.writeline (prod & " " & pname & " Version " & pver & " installed at " & ploc & " from " & psorce & " cached at " & pcache)
Next

我需要AlarmReciever类中的应用程序上下文,因为我打算发送通知。 教程设置的方式,使用AlarmReceiver,如:

public void startAlarm(View view) {
    Intent intent = new Intent(this, AlarmReciever.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this.getApplicationContext(), 234324243, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent);
}

我不确定如何传递上下文,因为我不使用构造函数。我错过了一些明显的东西,还是有其他方法可以做到这一点?

2 个答案:

答案 0 :(得分:1)

您应该将上下文传递给您的接收者:

public class AlarmReceiver extends BroadcastReceiver {

private Context context;
private PowerManager pm;
private PowerManager.WakeLock mWakeLock;

  @Override
  public void onReceive(Context context, Intent intent)
  {
    this.context = context;
    pm = (PowerManager)context.getSystemService(context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,TAG);
    wl.acquire();
            //....do your work. 


    wl.release();


   }
}

答案 1 :(得分:0)

您可以尝试这种方法:

只需通过扩展Application类创建一个应用程序实例:

public class App extends Application{ 

   private static Context mContext;

   @Override public void onCreate(){
       super.onCreate();

       App.mContext = getApplicationContext();
   }

   public static Context getAppContext(){
       return App.mContext;
   }
}

现在,在需要您的上下文的类中,只需执行此操作:

// somewhere in your code
App.getAppContext();

注意:您可能必须在AndroidManifest xml文件中设置Application属性并指向您的App类!

祝你好运,编码愉快!

相关问题