我正在使用
startService(new Intent(getApplicationContext(), NotificationService.class));
来自Activity
或BroadcastReceiver
(使用Context context
)。在每种情况下,服务都会启动,但服务也会启动MainActivity
。如何解决?服务代码:
public class NotificationService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
清单:
...
<activity
android:name=".ViewProfileActivity"
android:label="@string/title_activity_view_profile"
android:windowSoftInputMode="adjustResize|stateHidden" >
</activity>
<service
android:name=".NotificationService"
android:process=":NotificationService" >
</service>
...
UPD。广播接收器:
public class BootBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, NotificationService.class));
}
}
MainActivity从Application类的onCreate开始。
只需像这样在您的MainActivity中替换此代码:startForegroundService(Intent(applicationContext,MyService :: class.java));