在文件中添加 android:persistent="true"
...
<application>
android:persistent="true"
android:name="com.example.myservice.application.MyApplication"
...
<service>
android:name="com.example.myservice.MyServie"
...
</service>
</application>
...
在onCreate中添加:
public class MyApplication extends Application{ public void onCreate(){ super.onCreate(); //add-begin Intent intent = new Intent(); intent.setComponent(new ComponentName(com.example.myservice, com.example.myservice.MyService)); startServiceAsUser(intent, UserHandle.OWNER); //end-add } }
public class MyService extends Service{ private IBinder mBinder; public void onCreate(){ super.onCreate(); //add-begin if(mBinder == null){ mBinder = new MyManageImpl(); try{ ServiceManager.addService(com.example.myservice.MyService, mBinder); }catch(Exception e){ //nothing } } //end-add } public IBinder onBind(Intent intent){ return mBinder; } }