1

In android I want to start a service when an activity is created.

I'm getting this error:

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

I'm using the following code:

Service:

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);

    }
}

Activity:

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);
    }
}

androidmanifest:

 <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

サービス クラス ファイルをパブリック ID として作成します。

次に、この方法でアクティビティから呼び出します

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

サービスを停止したい場合は、コードを書き留めてください

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

Service クラスが public であることを確認してください。

于 2012-06-07T12:19:04.910 に答える
0

カスタム クラスがパブリックであり、引数のないパブリック コンストラクターがあることを確認してください。また、コンストラクターがスーパークラスのコンストラクターにチェーンされていることも確認してください。

于 2012-06-07T12:21:27.047 に答える