如果将多个意图传递给服务,如何从意图中获取bundle

时间:2015-03-25 02:44:35

标签: java android

我正在将意图传递给我的应用程序中两个不同位置的服务。一个intent有一个bundle,我想从中提取数据。但是当我尝试运行getIntent()。getExtras()方法时,我得到了NPE。

编辑: 在一堂课中:

                        basket.putString("KEY1", id[i]);
                        basket.putString("KEY2", message[i]);
                        basket.putString("KEY3", timeFormat[i]);
                        passNotiData = new Intent(getActivity(),
                                CheckService.class);
                        passNotiData.putExtras(basket);
                        startService(passNotiData);

在另一堂课中,

Intent myIntent = new Intent(context, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, myIntent, 0);
     context.startService(myIntent);

    mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + 60000, PERIOD, pi);

在服务类中,

Bundle gotBasket = intent.getExtras();
        oldId = gotBasket.getString("KEY1");
        oldTime = gotBasket.getString("KEY3");

1 个答案:

答案 0 :(得分:2)

//start service from activity or any place
Intent intent = new Intent(this, MyService.class);
            Bundle bundle = new Bundle();
            bundle.putString("TEST", "test got it.");
            intent.putExtras(bundle);
            startService(intent);


//In service class declare override method of service
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        if (intent != null && intent.getExtras() != null) {
            String str = intent.getExtras().getString("TEST");
            Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG)
                    .show();
        }
        return START_NOT_STICKY;
    }