android - 如何在由 AlarmManager 计划启动的服务中检索 Intent Extras?

标签 android android-intent android-service alarmmanager android-pendingintent

public void onCreate() {
    super.onCreate();
    int idFunc = getApplicationContext().getSharedPreferences(SPREF_NAME,Context.MODE_PRIVATE).getInt("idFunc", 0);
    String SecKey = getApplicationContext().getSharedPreferences(SPREF_NAME,Context.MODE_PRIVATE).getString("chave", null);
    Intent intent = new Intent(getApplicationContext(), ServiceEnviaClientes.class);
    Bundle bundle = new Bundle();
    bundle.putString("SecKey", SecKey);
    bundle.putInt("idFunc", idFunc);
    intent.putExtras(bundle);
    PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), 10*60000, pintent);
    initImageLoader(this);
}

我正在尝试从 AlarmManager Intent 传递 SharedPrefereces 提供的额外内容并在服务中检索它,而不是在服务运行时访问我的 SharedPreferences,我认为这需要更多内存。

 @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    Toast.makeText(this,"task perform in service",Toast.LENGTH_SHORT).show();
    Bundle bundle = intent.getExtras();
    mIdFunc = bundle.getInt("idFunc");
    mSecKey = bundle.getString("SecKey");
    ThreadJSONBuild td=new ThreadJSONBuild();
    td.start();
    Log.d(TAG, "onStartCommand cycle, idFunc: "+mIdFunc+" , SecKey: "+mSecKey);
    return super.onStartCommand(intent, flags, startId);
}

但我在 mSecKey 上得到了 null,在 idFunc 上得到了 0。我不确定这是否是最佳选择,我将我的 SharedPreferences 检索放在服务的 onCreate() 方法中,但不确定是否真的如此。

最佳答案

当你打电话时

PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0,
    intent, 0);

您可能会取回一个现有的 PendingIntent,但其中没有您的额外内容。你应该使用

PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0,
    intent, PendingIntent.FLAG_UPDATE_CURRENT);

相反。这将确保您的额外内容被放入 Intent 中。但是请注意,此 PendingIntent 的所有用户都将替换额外内容。

关于android - 如何在由 AlarmManager 计划启动的服务中检索 Intent Extras?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26676243/

相关文章:

java - 如何为带有交互式通知的网络广播流创建 Android 前台服务?

android - 选项卡布局 | TabIndicator 未选择的颜色

android - Lollipop 应用程序的透明导航栏?

android - Whatsapp错误音频/声音setResult Intent

java - 如何在 Android 中以编程方式查找当前正在运行的应用程序?

android - 服务绑定(bind)链

php - 如何解析 GCM 响应以使用 php 从服务器中删除无效的注册 ID

android - 加载由 ViewPager 管理的 Android 谷歌地图 fragment

java - Putextra 不断发送第一个输入的数据

android - 在 Lens 模式下打开 Android 上的谷歌助手