我创建了一个带有警报管理器和广播接收器的应用程序,我想要从主要活动到公共类的传递字符串MyScheduleReceiver扩展BroadcastReceiver(我有内部的警报管理器)然后到公共类MyStartServiceReceiver扩展BroadcastReceiver以传递数据到静态函数。 ..在主要活动中使用共享偏好从editbox保存此变量。但我不能在接收器内使用共享首选项。我怎么能这样做?
public class MyScheduleReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
int theHour = intent.getIntExtra("AlarmHour", 0);
int theMinute= intent.getIntExtra("AlarmMin", 0);
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyStartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
i.putExtra("data","1");
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, theHour); // set user selection
cal.set(Calendar.MINUTE, theMinute);
cal.set(Calendar.SECOND, 0);
service.set(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), pending);
}
public class MyStartServiceReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, AlarmService.class);
context.startService(service);
String result = intent.getStringExtra("data");
String msg=result;
try {
ArduBtTimer.sendData(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 0 :(得分:0)
试试这个:
where u want to set value:
i.putExtra("data",yourstring);
and for recieve:
String value = intent.getStringExtra("data");
答案 1 :(得分:0)
我认为您应该使用BroadCastReceiver发送要保存的信息并将其保存为SP 那里。
这是一个从接收者向活动发送信息的示例:
创建一个内部类,在您希望获取数据的活动中扩展BroadcastReceiver
:
private BroadcastReceiver ReceivefromService = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent)
{
//get the data using the keys you entered at the service
String IncomingSms=intent.getStringExtra("incomingSms");//
String phoneNumber=intent.getStringExtra("incomingPhoneNumber");
}
};
将此添加到onPause()
:
@Override
protected void onPause() {
super.onPause();
try {
unregisterReceiver(ReceivefromService);
} catch (IllegalArgumentException e) {
if (e.getMessage().contains("Receiver not registered")) {
Log.i("TAG","Tried to unregister the reciver when it's not registered");
}
else
{
throw e;
}
}
}
将此添加到onResume()
:
protected void onResume() {
super.onResume();
filter.addAction("android.intent.action.SmsReceiver");
registerReceiver(ReceivefromService, filter);
//the first parameter is the name of the inner class we created.
}
在接收器/服务中创建一个启动广播的意图,如下所示:
Intent i = new Intent("android.intent.action.SmsReceiver").putExtra("incomingSms", message);
i.putExtra("incomingPhoneNumber", phoneNumber);
context.sendBroadcast(i);
希望它会帮助你...