2017-02-21 95 views
1

我目前正在嘗試設置日期選擇器和時間選擇器,以在到達時間時發出通知。我在MainActivity中創建了一個方法,並且正在從AlarmReceiver中調用。每當計時器達到設定值時,應用程序崩潰並且logcat中不顯示錯誤。AlarmReceiver&通知方法導致崩潰?

我知道這是從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(); 

} 

} 

回答

3

通過這樣做MainActivity main = new MainActivity();你是剛剛創建的MainActivity一個實例,但它不會有它的context意味着thisActivityOS

開始它基本上設置所以請將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()); 
    } 

} 
+0

感謝您的回覆,我已將其移交給AlarmReceiver。現在只有一個錯誤顯示getSystemService。無法解析方法'getSystemService(java.lang.String)' – ZenoX

+0

@ZenoX使用'cxt.getSystemService..' –

+0

非常感謝您的幫助。我剛剛測試過,通知現在正在被觸發!另外感謝您解釋MainActivity代碼作爲一個實例,它真的幫助我理解! – ZenoX