android 应用小部件的编程功能

Programming functionality for an android app widget

我有一个简单的手电筒应用程序,我也想通过简单地单击小部件来实现电灯开关功能。

现在,当我点击小部件时,我的程序启动了,没问题,但直接从小部件访问我的应用程序的功能会更好。

我认为现在 appwidgetprowider 刚刚启动我的 activity:

Intent intent = new Intent(context, MainActivity.class);

在我手电筒的主 activity 中,我通过

打开 phone 的 LED

switchOnTheFlash()

方法。

有没有人知道,我怎样才能从小部件启动这个方法?

谢谢您,并致以最诚挚的问候!

打开手电筒不需要意图,因为它总是会带您进行活动或行动。最简单的做法是让你的 switchOnTheFlash() 函数 static 像这样 -

public static void switchOnTheFlash() {
    // Your Function
}

现在您可以从任何 activity 调用此函数,就像 -

YourACtivity.switchOnTheFlash();

如果出现错误--

确保你在 switchOnTheFlash() 中使用的所有变量也应该是 static 否则你会得到像 cannot use non-static variables in static function 这样的错误(或者可能有点写的有点不一样)。

另一个错误,如果你使用像getResources()这样的函数,你会得到错误。要摆脱,只需全局创建一个 static Context mContext; 并像 OnCreate 中的 mContext = this; 一样初始化它。然后只需在函数 switchOnTheFlash().

的任何地方替换 mContext.getResources()...

干杯!