2013-10-09 45 views
0

我必須通過AlaramManager調用我的BroadcastReceiver。使用AlarmManager調用我的BraodcastReceiver? [DONE]

這個我做什麼,不工作:

AlarmActivity.java

public class AlarmActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_alarm); 

     AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 

     Calendar calendar = Calendar.getInstance(); 
     calendar.set(Calendar.HOUR_OF_DAY, 12); 
     calendar.set(Calendar.MINUTE, 50); 
     calendar.set(Calendar.SECOND, 0); 

**Edit : Solution** 

     //Intent intent = new Intent(AlarmActivity.this, MyService.class); 
     //PendingIntent pendingIntent = PendingIntent.getService(AlarmActivity.this, 0, intent, 0); 
     //alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
     //alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, c.getTimeInMillis(), pendingIntent); 

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    Intent intent1 = new Intent(AlarmActivity.this, MyService.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, intent1,PendingIntent.FLAG_UPDATE_CURRENT); 
    am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); 
    } 
} 

MyService.java

public class MyService extends BroadcastReceiver { 

    @SuppressLint("SimpleDateFormat") 
    @Override 
    public void onReceive(Context arg0, Intent arg1) { 
      Log.e("Broadcast", "Done"); 
    } 
} 

Also give alarm permission and receiver

這是我用過但沒有工作。你能告訴我錯過了什麼嗎?

回答

1

使用本

AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
       Intent intent1 = new Intent(Scheduling.this, Feedback.class); 
       PendingIntent pendingIntent = PendingIntent.getBroadcast(Scheduling.this, 0, intent1,PendingIntent.FLAG_UPDATE_CURRENT); 
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar1.getTimeInMillis(), 86400000, pendingIntent);     

外接接收器menifest

+0

,我通過這個。那這個呢 ? –

+0

沒有它定義,當手機重新啓動它會自動啓動 – Rohit

+1

完成:)沒有接收器問題,其實pendingIntent是問題 –

0

不喜歡這樣,

public class MyService extends BroadcastReceiver { 
private Context mContext; 
    @SuppressLint("SimpleDateFormat") 
    @Override 
    public void onReceive(Context arg0, Intent arg1) { 
      StringBuilder msgStr = new StringBuilder(); 
      Format formatter = new SimpleDateFormat("hh:mm:ss a"); 
      msgStr.append(formatter.format(new Date())); 
      Log.e("Broadcast", "Done"); 
      mContext = arg0; 
    } 
} 

在getSystemservice()寫這樣的代碼,

AlarmManager am = (AlarmManager) mContext.getSystemService(mContext.ALARM_SERVICE); 
+0

什麼是C這裏 ? –

+0

我應該把廣播的上下文傳遞給主活動 –

+0

@AM我編輯了代碼,看看它。 –