2012-06-07 107 views
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); 
    } 
} 

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> 
+0

從您的活動調用[This](http://stackoverflow.com/questions/3278091/android-java-lang-illegalaccessexception-when-attempting-to-use-a-custom-appli)可能會幫助你。 –

回答

3

讓你的服務類文件作爲公共identifire

然後通過這種方式

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

,如果你要停止你的服務剛放下代碼

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

確保您的Service類是公共的。

0

請看看您的自定義類是公共的,並且它有一個公共的零參數構造函數,也查看構造函數鏈的超類的構造函數。

+0

複製粘貼[從這裏?](http://stackoverflow.com/questions/3278091/android-java-lang-illegalaccessexception-when-attempting-to-use-a-custom-appli)? –

+0

嗨samir實際上,當我在這個領域新鮮我也面臨這個問題,所以我從這裏搜索並實施:)這是有益的,所以我回答了 –

+0

@then你應該把評論? –