Android 基本组件及其交互

#移动开发 #Android

一、Android 的基本组件

1. Activity
应用程序中每个屏幕显示都通过继承和扩展基类 Activity
在一个应用程序中每个 Activity 都是独立的

2. Service
Service 是没有可见的用户界面,但可以长时间在后台运行

3. Broadcast
用户接受广播通知的组件,广播是一种同时通知多个对象的事件通知机制
应用程序注册不同的 Broadcast Receiver,从而接收不同广播通知
不实现图形界面

4. Content Provider
应用程序彼此间需要共享资源,数据通讯时,采用 content provider 机制
它能将应用程序特写的数据提供给另一个应用程序使用

二、组件间的通讯

1. ContentProvider 用于提供,ContentResolver 用于调用

2. Intent
用于在不同组件间传递消息:Activity, Service, Broadcast
Intent 一般带有一个组件对另一组件的请求的动作名称,请求动作及相关数据

  1. Activity 相互调用
    Intent in = new Intent(ac01.this, pickup.class);
    startActivity(in);

  2. Activity 与 Broadcast 相互调用
    public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent)
    {
    ac01 app = ac01. getApp ();
    app.btEvent("from AlarmReceiver");
    }
    }
    Intent intent = new Intent(ac01.this, AlarmReceiver.class);
    PendingIntent p_intent = PendingIntent. getBroadcast (ac01.this, 0, intent,

0);
// We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock. elapsedRealtime ();
firstTime += 800;
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager. ELAPSED_REALTIME_WAKEUP, firstTime, 800,

p_intent);

  1. Activity 与 Service 相互调用
    public class NotifyService extends Service{
    @Override
    protected void onCreate() {
    ac01 app = ac01. getApp ();
    app.btEvent("from NotifyService");
    }
    @Override public IBinder onBind(Intent intent) { return null; }
    }
    context.startService(new Intent(context, NotifyService.class));