如何从服务到活动进行数据传输?

时间:2013-03-07 05:01:20

标签: android service

我有多个应用程序和单个服务,我想在应用程序和服务之间创建通信。我正在保存应用程序已发送的服务中的值。现在我试图通过服务中的另一个应用程序读取相同的值。

如何实现这一目标?我不想从服务中调用显式意图,也不想隐式意图,因为隐式意图会给出一个选择选项来选择我想要的所需应用程序。请指教。

2 个答案:

答案 0 :(得分:0)

您可以使用Broadcast Receivers来完成这项工作。您不需要后台服务来执行此操作。您可以触发一个intent,注册指定的intent过滤器的其他应用程序也可以使用它。

答案 1 :(得分:0)

使用BroadcastReceiver,

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            //              Bundle bundle = intent.getExtras();
            //          String message = bundle.getString("alarm_message");
            //                  Toast.makeText(context,bundle.getString("eventName"), Toast.LENGTH_SHORT).show();

            NotificationManager notificationManager =(NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
            int icon = R.drawable.event;
            CharSequence notiText = "Event Notification";
            long time = System.currentTimeMillis();
            @SuppressWarnings("deprecation")
            Notification notification = new Notification(icon, notiText,time);
            notification.defaults |= Notification.DEFAULT_SOUND;
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            Intent notificationIntent = new Intent(context, Setting.class);
                     //put data in notificationIntent ....>>>>>



            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
            notification.setLatestEventInfo(context,intent.getStringExtra("eventName"),intent.getStringExtra("eventDescription"), contentIntent);
            int SERVER_DATA_RECEIVED =  1;
            Calendar cal=Calendar.getInstance();
            Toast.makeText(context,"aavechhe "+intent.getBooleanExtra("Flag",false),Toast.LENGTH_SHORT).show();
            if(intent.getIntExtra("month",0)==cal.get(Calendar.DAY_OF_MONTH))
            {
                Toast.makeText(context,"aavechhe "+cal.get(Calendar.DAY_OF_MONTH),Toast.LENGTH_SHORT).show();
                notificationManager.notify(SERVER_DATA_RECEIVED, notification);
            }
            if(intent.getBooleanExtra("Flag",false))
                notificationManager.notify(SERVER_DATA_RECEIVED, notification);

        } catch (Exception e) {
            Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
            e.printStackTrace();

        }
    }
}