我有一个复选框列表,用户选择一些项目,然后我在json格式中封装他的选择,随后我从alarmManager发射json字符串,然后试图将其发送到GetLLRD
IntentService类,但我面临的问题是,我没有在GetLLRD类中接收意图,因为我没有在GetLLRD类中获得任何输出。
我该如何修复它?
MainActivity:
Intent intentJson = new Intent(MainActivity.this, GetLLRD.class);
intentJson.putExtra("json_data", json);
PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 3, intentJson, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
5 * 1000, pintent);
System.out.println("test intentJson output: " +intentJson);
startService(intentJson);
GetLLRD类:
public class GetLLRD extends IntentService {
public GetLLRD(String name) {
super(name);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String jSONString = intent.getStringExtra("json_data");
System.out.println("test json is " + jSONString);
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
String jSONString = intent.getStringExtra("json_data");
System.out.println("Test" + jSONString);
if(jSONString != null){
System.out.println("Test");
}
}
}
你必须在pending intent中注册广播接收器。你可能在服务中创建挂起意图是错误的。为了得到通知从报警管理器我们需要使用广播接收器。
注册AlarmManager
int REQUEST_CODE= 0;
Calendar calendar = Calendar.getInstance();
int hour = 13;
int minute = 00;
calendar.set(Calendar.HOUR_OF_DAY, hour);//24 Hour format
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 00);
/*calendar.set(Calendar.AM_PM, peried.equalsIgnoreCase("AM") ? Calendar.AM : Calendar.PM);*/
Intent myIntent = new Intent(context, MyReceiver.class);
myIntent.putExtra("json_data", json);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
5 * 1000, pendingIntent );
接收机
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getStringExtra("json_data");
new ShowToast(context, action);
if (action.length() > 1) {
startService(context, action);
}
} catch (Exception e) {
}
}
public void startService(Context context, String action) {
Intent service1 = new Intent(context, GetLLRD.class);
service1.putExtra("json_data", action);
context.startService(service1);
}
}
在manifest中注册receiver并请求使用AlarmManager权限
<uses-permission android:name="android.permission.WAKE_LOCK" />
<receiver android:name=".MyReceiver" />