我目前正在尝试设置日期选择器和时间选择器,以便在到达时间时发出通知。我在MainActivity中创建了一个方法,这是从AlarmReceiver调用的。每次计时器达到设定的数量时,应用程序都会崩溃,并且logcat中没有显示任何错误。
我知道这是从AlarmReceiver调用此方法的事情,我只是不知道问题是什么。此方法当前也链接到按下时按下的按钮(buttonStopAlarm)按需要按下时触发通知)所以整个方法确实有效,从另一个类调用它时就不起作用了。
任何帮助将不胜感激!谢谢!
AlarmReceiver
package servicealarmdemo.test2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
MainActivity main = new MainActivity();
@Override
public void onReceive(Context arg0, Intent arg1) {
Toast.makeText(arg0, "Alarm received!", Toast.LENGTH_LONG).show();
main.addNotification();
}
}
答案 0 :(得分:3)
通过执行此操作MainActivity main = new MainActivity();
,您只是创建MainActivity
的实例,但它不会context
意味着this
,这基本上是Activity
{1}}由OS
所以在Notification code
移动你Receiver
并使用arg0
作为context
public class AlarmReceiver extends BroadcastReceiver {
//MainActivity main = new MainActivity();
Context cxt;
@Override
public void onReceive(Context arg0, Intent arg1) {
Toast.makeText(arg0, "Alarm received!", Toast.LENGTH_LONG).show();
cxt = arg0;
//main.addNotification();
addNotification();
}
public void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(cxt)
.setSmallIcon(R.drawable.icon_transperent)
.setContentTitle("Achieve Alert!")
.setContentText("This is a reminder for your deadline!");
Intent notificationIntent = new Intent(cxt, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(cxt, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager)cxt.getSystemService(Context.NOTIFICATION_SERVICE);
builder.setVibrate(new long[] { 0, 1000, 1000, 1000, 1000 });
manager.notify(0, builder.build());
}
}