如何从选项菜单启动服务

时间:2013-11-30 07:33:53

标签: android android-intent android-activity android-service optionmenu

我想点击选项菜单项启动服务。

 public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    menu.add("Help").setIcon(R.drawable.HelpActivity).setIntent(new Intent(this,HelpActivity.class));//this is activity intent .It works fine
    menu.add("Update Media").setIcon(R.drawable.update_icon).setIntent(new Intent(this,MediaUpdate.class));//this is service intent.It dose not works

return super.onCreateOptionsMenu(menu);
}

清单

    </service>
            <service android:name="com.Dexter.otp.services.MediaUpdate" >
    </service>

点击更新媒体我收到日志错误

11-30 12:46:10.775: E/MenuItemImpl(4918): Can't find activity to handle intent;   ignoring
11-30 12:46:10.775: E/MenuItemImpl(4918): android.content.ActivityNotFoundException:  Unable to find explicit activity class   {com.Dexter.otp/com.Dexter.otp.services.MediaUpdate}; have you declared this activity in your AndroidManifest.xml?

似乎无法通过菜单项启动服务/广播。

1 个答案:

答案 0 :(得分:2)

如果这不起作用,您还可以尝试设置onclicklistener并调用startService

menu.add("setting").setOnMenuItemClickListener(
            new OnMenuItemClickListener() {

                @Override
                public boolean onMenuItemClick(MenuItem arg0) {
                    [Activtyname].this.startService(new Intent(this, MediaUpdateService.class));
                    return false;
                }
            });