(1) 从一个活动中,我可以调用我的 IntentService 的特定方法(动作)吗?使用下面的示例代码,我想只调用 ACTION_BAZ:
public class MyIntentService extends IntentService {
private static final String ACTION_FOO = "com.example.application.action.FOO";
private static final String ACTION_BAZ = "com.example.application.action.BAZ";
private static final String EXTRA_PARAM1 = "com.example.application.extra.PARAM1";
private static final String EXTRA_PARAM2 = "com.example.application.extra.PARAM2";
public static void startActionFoo(Context context, String param1,
String param2) {
Intent intent = new Intent(context, MyIntentService.class);
intent.setAction(ACTION_FOO);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
public static void startActionBaz(Context context, String param1,
String param2) {
// pretty much identical
}
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_FOO.equals(action)) {
final String param1 = intent.getStringExtra(EXTRA_PARAM1);
final String param2 = intent.getStringExtra(EXTRA_PARAM2);
handleActionFoo(param1, param2);
} else if (ACTION_BAZ.equals(action)) {
final String param1 = intent.getStringExtra(EXTRA_PARAM1);
final String param2 = intent.getStringExtra(EXTRA_PARAM2);
handleActionBaz(param1, param2);
}
}
}
private void handleActionFoo(String param1, String param2) {
// populates sqldatabase tables from asset .csv file
}
private void handleActionBaz(String param1, String param2) {
// compliments onUpgrade database action by dropping tables in ActionFoo
}
}
(2) 根据我的活动,我可以/应该打电话吗?
public void onCreate(SQLiteDatabase db)
{
db.execSQL(SQL_CREATE_TABLE);
// Starts MyIntentService queue for populating Table
final Context svccontext = svccontext.getApplicationContext();
final Intent intent = new Intent(svccontext, MyIntentService.class);
intent.setAction(ACTION_FOO);
svccontext.startService(intent);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// the same as above, but calls method to drop tables
intent.setAction(ACTION_BAZ);
}
但是,如果我没有使用 (1) 的 IntentService 的方法(操作)中指定的参数 param1 和 param2 调用该方法,会不会有问题?
(3) 最后,在Google (deveoper.android.com)提供的示例代码中,我的 IntentService 是否总是按顺序启动方法(操作)Foo 和 Baz?如果我完全离开,请纠正我的理解......
我的意思是调用 myIntentService 作为后台服务来执行不会延迟 UI 的数据库功能。我可能有
ActionFoo 填充我的 MainActivity 从资产 .csv 文件创建的表。
在我的 MainActivity 的 onUpgrade 调用中,ActionBaz 可以删除上述表格。
用户仍然可以在用户定义的表中手动输入数据,而后台可以处理资产填充的表。
所以我的第三个问题是:对 myIntentService 的所有调用都会执行 ActionFoo(填充表)和 ActionBaz(从而删除我刚刚创建的表)吗?还是我的 onHandleIntent 会确保仅对指定的 Action(添加到意图)进行操作?
如果我必须在我的 Activity 中明确提及意图的 setAction 和参数,我的 IntentService 的辅助方法(即 startActionFoo)有什么帮助?无论如何,它们都必须重新定义到调用活动中。