Android:如何将数据从Activity传递到Service?

时间:2014-09-28 18:20:57

标签: android android-intent broadcastreceiver android-service

我的申请是在任何特定时间发出通知。我正在使用notificationManager所在的BroadcastReceiver和Service类。 我需要将一些数据(项目标题)传递给通知。 什么是最好的方法?

这是主要活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day);

Intent myIntent = new Intent(Config.context, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(Config.context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager)Config.context.getSystemService(Config.context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeInMillis, 24 * 60 * 60 * 1000, pendingIntent);
}

这是我的BrodacastReceiver

public class MyReceiver extends BroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent)
    {
        String title = intent.getStringExtra(DayActivity.EXTRA_TITLE);
        Intent service1 = new Intent(context, MyAlarmService.class);
        context.startService(service1);

    }    
}

这里是服务类

@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId)
        {
            super.onStart(intent, startId);

            mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
            Intent intent1 = new Intent(this.getApplicationContext(),DayActivity.class);

            Notification notification = new Notification(R.drawable.notification_logo, "Title", System.currentTimeMillis());
            intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

            PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.setLatestEventInfo(this.getApplicationContext(), "Title", "Message!", pendingNotificationIntent);

            mManager.notify(0, notification);
        }

我尝试使用额外的意图但是当应用程序关闭时它不起作用。

1 个答案:

答案 0 :(得分:1)

启动服务时只需将捆绑包放到该服务意图

在接收者中:

    String title = intent.getStringExtra(DayActivity.EXTRA_TITLE);
    Intent service1 = new Intent(context, MyAlarmService.class);
    Bundle dataBundle=new Bundle();
    dataBundle.putString("key","value");
    context.startService(service1);

在服务中:

    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
        Bundle dataBundle=intent.getExtras();
        String value=dataBundle.getString("key");
    }