Post

【Android】Service

  • Service相当于一个没有图形界面的Activity,主要功能是为Activity程序提供一些必要的支持,例如mp3播放软件等。
  • 声明Service类:
1
2
3
4
5
6
public class MyService extends Service {
    @Override public void onCreate() { }
    @Override public int onStartCommand(Intent intent, int flags, int startId) { ... }
    @Override public void onDestroy() { }
    @Override public IBinder onBind(Intent intent) { return null; }
}
  • Service也是组件,需要在AndroidManifest.xml表单文件中配置:
1
<service android:name=".MyService" />
  • 启动Service:startService(new Intent(MainActivity.this, MyService.class));
  • 停止Service:stopService(new Intent(MainActivity.this, MyService.class));
  • 绑定Service:将前台Activity界面与后台Service绑定(生命周期相同,同生共死),则Activity退出时与它绑定的Service自动停止。使用ServiceConnection接口:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private ServiceConnection serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        try {
            System.out.println("### Service Connect Success = "
                    + iBinder.getInterfaceDescriptor());
        }
        catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        System.out.println("### Service Failure.");
        // 断开连接,但Service仍在后台运行
    }
};
  • 绑定:bindService(new Intent(MainActivity.this, MyService.class), serviceConnection, Context.BIND_AUTO_CREATE);
  • 解除绑定:unbindService(serviceConnection);
  • Android提供了很多种系统服务:Object getSystemService(String name)
name返回的对象说明
ACTIVITY_SERVICEActivityManager管理应用程序的系统状态
ALARM_SERVICEAlarmManager闹钟的服务
CLIPBOARD_SERVICEClipboardManager剪贴板服务
CONNECTIVITY_SERVICEConnectivity网络连接的服务
KEYGUARD_SERVICEKeyguardManager键盘锁的服务
LAYOUT_INFLATER_SERVICELayoutInflater取得xml里定义的view
LOCATION_SERVICELocationManager位置的服务,如GPS
NOTIFICATION_SERVICENotificationManager状态栏的服务
POWER_SERVICEPowerManger电源管理服务
SEARCH_SERVICESearchManager搜索服务
TELEPHONY_SERVICETeleponyManager电话服务
VEBRATOR_SERVICEVebrator手机震动的服务
WIFI_SERVICEWifiManagerWi-Fi服务
WINDOW_SERVICEWindowManager管理打开的窗口程序
This post is licensed under CC BY 4.0 by the author.