1

在android中,我想在创建活动时启动服务。

我收到此错误:

E/AndroidRuntime(1433): Caused by:
    java.lang.IllegalAccessException: access to class not allowed

我正在使用以下代码:

服务:

class Myservice extends Service 
{
    @Override
    public void onCreate() {
        Log.d("Debug", "on create delete sms");
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onDestroy() {
          super.onDestroy();
          Log.d("Debug", "on destroy delete sms");
        }

    @Override
    public void onStart(Intent intent1, int startId) {

        Log.d("Debug", "on start delete sms");
        super.onStart(intent1, startId);

    }
}

活动:

public class ServicetestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        Intent serviceIntent = new Intent();
        serviceIntent.setAction("org.avd.Myservice");
        getApplicationContext().startService(serviceIntent);
    }
}

机器人清单:

 <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ServicetestActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="org.avd.Myservice">
        <intent-filter>
                        <action android:name="org.avd.Myservice" />
           </intent-filter>
        </service>
    </application>
4

3 回答 3

3

将您的服务类文件设为公共标识

然后通过这种方式从您的活动中调用

startService(new Intent("yourActivity.this",Myservice .class));

如果您想停止服务,只需输入代码

stopService(new Intent("yourActivity.this",Myservice .class));
于 2012-06-07T12:32:06.457 回答
0

确保您的服务类是公开的。

于 2012-06-07T12:19:04.910 回答
0

请注意您的自定义类是公共的,并且它有一个公共的零参数构造函数,还请查看构造函数链接到超类的构造函数。

于 2012-06-07T12:21:27.047 回答