源码示例如下:
ServiceExample .java
public class ServiceExample extends Service {
final private String LOG_TAG = "ServiceExample ";
private BroadcastReceiverHelper rhelper;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
rhelper=new BroadcastReceiverHelper(this);
rhelper.registerAction("android.intent.action.menulongpress");
}
@Override
public void onDestroy() {
super.onDestroy();
rhelper.unregisterAction("android.intent.action.menulongpress");
}
...
}
要启动某个service, 如下示例:
...
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.example.android.home.menu_longPressService");
startService(serviceIntent);
serviceIntent.setAction("com.android.phone");
startService(serviceIntent);
如要在Service中启动某个Activity, 示例如下(注意设置FLAG_ACTIVITY_NEW_TASK):
xxxActivity tb = new xxxActivity();
intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(context, tb.getClass());
startActivity(intent);