ExtensionService 像其他 android 服务一样工作。只是通过Context
实例向您的通知服务发送意图。
public class SampleExtensionService extends ExtensionService {
public static final String EXTENSION_KEY = "sample.app";
public static final String EXTENSION_SPECIFIC_ID = "notification.id";
public static final String INTENT_ACTION_ADD = "add";
public static final String EXTRA_EVENT_CONTENT = "extra.eventcontent";
public SampleExtensionService() {
super(EXTENSION_KEY);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int retVal = super.onStartCommand(intent, flags, startId);
if ((intent != null) && (intent.getAction().equals(INTENT_ACTION_ADD))) {
if (intent.getExtras() != null) {
displayEvent(intent.getExtras());
}
}
return retVal;
}
private void displayEvent(Bundle extras) {
long sourceId = NotificationUtil.getSourceId(this, EXTENSION_SPECIFIC_ID);
if (sourceId == NotificationUtil.INVALID_ID) {
return;
}
ContentValues values = new ContentValues();
values.put(Notification.EventColumns.DISPLAY_NAME, "New event");
values.put(Notification.EventColumns.MESSAGE, extras.getString(EXTRA_EVENT_CONTENT));
values.put(Notification.EventColumns.PERSONAL, 1);
values.put(Notification.EventColumns.PUBLISHED_TIME, System.currentTimeMillis());
values.put(Notification.EventColumns.SOURCE_ID, sourceId);
getContentResolver().insert(Notification.Event.URI, values);
}
}
从这个活动中,我们为我们的服务发送意图
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button sendButton = (Button) findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SampleExtensionService.class);
intent.setAction(SampleExtensionService.INTENT_ACTION_ADD);
Bundle extras = new Bundle();
extras.putString(SampleExtensionService.EXTRA_EVENT_CONTENT, "Some event content");
intent.putExtras(extras);
startService(intent);
}
});
}
}
对于通知,您必须实现 getSourceRegistrationConfigurations()
public class SampleRegistrationInformation extends RegistrationInformation {
final Context mContext;
protected SampleRegistrationInformation(Context context) {
mContext = context;
}
@Override
public int getRequiredNotificationApiVersion() {
return 1;
}
@Override
public ContentValues getExtensionRegistrationConfiguration() {
<..>
}
@Override
public ContentValues[] getSourceRegistrationConfigurations() {
ContentValues sourceValues = new ContentValues();
sourceValues.put(Notification.SourceColumns.ENABLED, true);
sourceValues.put(Notification.SourceColumns.NAME, "Sample");
sourceValues.put(Notification.SourceColumns.EXTENSION_SPECIFIC_ID, SampleExtensionService.EXTENSION_SPECIFIC_ID);
sourceValues.put(Notification.SourceColumns.PACKAGE_NAME, mContext.getPackageName());
return new ContentValues[]{sourceValues};
}
}