在非activity中调用startservice

首先在application中添加context静态常量

public class App extends Application {

    private static Context appContext;

     public void onCreate() {
        super.onCreate();
	appContext = getApplicationContext();
     }

     public static Context getContext() {
        return appContext;
    }
}

在需要调用service的地方

private ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //--TODO
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            //--TODO
        }
};

 private void bindServiceConnection() {
        Intent intent = new Intent(mWXSDKInstance.getContext(), MusicService.class);
        App.getContext().startService(intent);
        App.getContext().bindService(intent, sc, Activity.BIND_AUTO_CREATE);
}

猜你喜欢

转载自blog.csdn.net/fenfeng2012/article/details/80997366
今日推荐