在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 :(得分:3)
将您的服务类文件设为公共标识
然后以这种方式从你的活动中打电话
startService(new Intent("yourActivity.this",Myservice .class));
如果你想停止服务,只需记下代码
stopService(new Intent("yourActivity.this",Myservice .class));
答案 1 :(得分:0)
确保您的服务类是公开的。
答案 2 :(得分:0)
请查看您的自定义类是公共的,它有一个公共零参数构造函数,也看起来构造函数链到超类的构造函数。