2016-02-29 62 views
0

我需要從主活動傳遞字符串值到實現BroadcastReceiver的Java類。基本上我想從AddNewPrescriptionsActivity.java中的EditText獲得一個String值並將其傳遞給AlarmReceiver.java。看來我不能使用Intent或Bundle來傳遞它,所以還有另一種方法來做到這一點?我有我的一些下面代碼..從活動傳遞字符串到Java類

下面是我的一些MainActivity稱爲AddNewPrescriptionsActivity.java的:

 public void onClick(View v) { 

     if (v == btnSave) { 
     calSet.getTime(); 
     if (calSet.compareTo(calNow) <= 0) { 
     //Today Set time passed, count to tomorrow 
      calSet.add(Calendar.DATE, 1); 
     } 
     setAlarm(calSet); 
     Toast.makeText(AddNewPrescriptionsActivity.this, "Notification Created", Toast.LENGTH_LONG).show(); 

         } 
        } 


    private void setAlarm(Calendar targetCal) { 

    Intent intent = new Intent(getBaseContext(), AlarmReceiver.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0); 
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent); 

} 

這裏是我的AlarmReceiver.class它實現了廣播接收器提前

public class AlarmReceiver extends BroadcastReceiver { 

    @Override 
public void onReceive(Context arg0, Intent arg1) { 

     Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     Ringtone r = RingtoneManager.getRingtone(arg0, notification); 
     r.play(); 

     Toast.makeText(arg0, "Received" , Toast.LENGTH_LONG).show(); 


}} 

謝謝!

回答

0

如果我很好地理解你的問題,你需要從你的活動發送一個字符串值到你的廣播接收器。要做到這一點,在你的活動:

Intent in = new Intent("my.action.string"); 
    in.putExtra("state", "activated"); 
    sendBroadcast(in); 

而且廣播接收器內:

@Override 
public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 

    Log.i("Receiver", "Broadcast received: " + action); 

    if(action.equals("my.action.string")){ 
    String state = intent.getExtras().getString("state"); 
    //do your stuff 
    } 
} 

而且裏面manifest.xml中:

<receiver android:name=".YourBroadcastReceiver" android:enabled="true"> 
<intent-filter> 
    <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
    <action android:name="my.action.string" /> 
    <!-- and some more actions if you want --> 
</intent-filter> 

希望它能幫助!

+0

這看起來可能有幫助,但在運行時它仍然崩潰。我將編輯我的問題以嘗試更具體。 –

+0

如果它確實崩潰!告訴你在日誌貓中獲得什麼! – OBX

相關問題