我按照this example设置闹钟。
这是 MainActivity 类扩展了Droidgap
@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" }) public class MainActivity extends DroidGap {
//CordovaWebView cwv;
final static public long ONE_SECOND = 1000;
final static public long TWENTY_SECONDS = ONE_SECOND * 20;
public PendingIntent pi;
public BroadcastReceiver br;
public AlarmManager am;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView =new WebView(this);
//enabling javascript call to native code
webView.getSettings().setJavaScriptEnabled(true);
webView.setClickable(true);
//Give name to interface class, "Reminder" will call through javascript
webView.addJavascriptInterface(new MainActivity(), "Reminder");
webView.loadUrl("file:///android_asset/www/index.html");
setContentView(webView);
}
这项工作很好,它设置了警报和正确的火力,
@Override
public void onStart(){
super.onStart();
setup();
am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +
TWENTY_SECONDS, pi ); //This code works
}
虽然我尝试通过javascript调用另一个方法有相同的代码,但它给出了NullPointerException,这是我的JavascriptInterface,
@JavascriptInterface
public void showToast(String mssg) {
Log.v("AlrmMNG", am.toString());//Even this log is not working
am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +
TWENTY_SECONDS, pi );
Log.v("Alarm end", "Alarm set");
}
这是 logcat ,
03-05 12:25:58.330: E/AndroidRuntime(3444): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-05 12:55:59.710: W/System.err(3640): java.lang.NullPointerException
03-05 12:55:59.710: W/System.err(3640): at com.agrando.reminder_level1.MainActivity.showToast(MainActivity.java:67)
03-05 12:55:59.710: W/System.err(3640): at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
03-05 12:55:59.720: W/System.err(3640): at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:27)
03-05 12:55:59.730: W/System.err(3640): at android.os.Handler.dispatchMessage(Handler.java:102)
03-05 12:55:59.730: W/System.err(3640): at android.os.Looper.loop(Looper.java:136)
03-05 12:55:59.730: W/System.err(3640): at android.os.HandlerThread.run(HandlerThread.java:61)
03-05 12:55:59.830: I/chromium(3640): [INFO:CONSOLE(25)] "Uncaught Error: Error calling method on NPObject.", source: file:///android_asset/www/index.html (25)
我尝试了几种不同的方法但结果相同。(我没有在这里添加setup()代码,你可以从上面给出的链接中找到它。)请帮助**
* 以下是link to project files * **
答案 0 :(得分:1)
am
AlarmManager
的{{1}}实例在您使用之前忘记初始化之前为null
,所以请执行以下操作:
am=(AlarmManager)MainActivity.this.getSystemService(Context.ALARM_SERVICE);