各位大侠好,我的Service可以在主线程启动,输出显示只执行了 onCreate 方法,Service 的 onStart 有一条删除线。但是如果用 BroatcastReceiver 来启动的话,onCreate 也没有输出,请问这是为什么呢?下面是代码:
MyBroadcastReceiver.java
public class MyBroadcastReceiver extends BroadcastReceiver {
private final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, context+"");
Intent i = new Intent(context, NofyService.class);
i.addCategory(Intent.CATEGORY_DEFAULT);
//context.startService(i);
Log.v(TAG, context.startService(intent)+"");
Log.v(TAG, "Receiv");
}
}
NofyService.java
public class NofyService extends Service {
private final String TAG = "NofyService";
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Log.v(TAG, "onCreate");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.v(TAG, "onstart");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cj_finger.dyfin">
<permission android:protectionLevel="normal" android:name=".service.NofyService"></permission>
<!-- 权限 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!-- 首页 -->
<activity android:name=".activity.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 新建日程表 -->
<activity android:name=".activity.NewActivity">
</activity>
<!-- 编辑日程表 -->
<activity android:name=".activity.EditActivity">
</activity>
<!-- 接收广播 -->
<receiver android:name=".broadcastReceiver.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.MY_BROADCAST"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<!-- 服务 -->
<service
android:permission=".service.NofyService"
android:enabled="true"
android:name=".service.NofyService"
android:process="com.cj_finger.dyfinService" >
<intent-filter>
<action android:name=".service.NofyService"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
</application>
</manifest>