【问题标题】:Background Service without Activity没有活动的后台服务
【发布时间】:2013-10-24 15:01:11
【问题描述】:

我正在尝试创建一个使用后台服务连接到 BluetoothDevice 的应用程序:

活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);


    /* ... Create Data Scruct ...*/
    dataStruct = new DataStruct();

    /* Start Service /*
    Intent intentService = new Intent(this,NewService.class);
    intentService.putExtra("Data", dataStruct);
    startService(intentService);


}

服务:

public class NewService extends Service{
@Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      super.onStartCommand(intent, flags, startId); 
dataStruct = intent.getStringExtra("Data");
...
connectBluetooth(dataStruct.getDeviceBT());
return START_NOT_STICKY;
}

public void BTReceive(){
updateDataStruct();
}
}

每当 BT 连接并接收到一些特殊的东西时,就会发生通知 单击通知时,活动开始(按意图) 它可以工作,但我想在没有启动 Activity 布局的情况下启动这个应用程序。我想启动服务并在移动启动时启动它。 最后一个问题,当我从“最后一个应用程序列表”中刷出应用程序时,服务停止并且蓝牙通信丢失。 有办法避免吗? 我想杀死 Activity 但保持存活服务

谢谢

【问题讨论】:

    标签: service android-activity swipe kill


    【解决方案1】:

    *) 我想只启动服务并在移动启动时启动它。?

    答案:使用下面这段代码在启动时启动服务。

    <receiver
            android:name="com.xxx.CustomBroadcastReciever"
            android:enabled="true" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>
    

    使用广播接收器在启动或启动完成时接收意图,然后从那里启动您的服务。

    *) 当我从“最后一个应用程序列表”中刷出应用程序时,服务停止并且蓝牙通信丢失。有办法避免吗?

    答案:使用 AlarmManager 来避免它。使用运行非常 5 - 10 秒的重复警报,从那里您可以调用 BroadCastReceiver。所以现在广播接收器被称为非常 5-10 秒。检查服务是否仍在运行,否则在 BroadCastReceiver 中启动它。

    Intent intent = new Intent(this, CustomBroadcastReciever.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
    
            // InexactRepeating allows Android to optimize the energy
            // consumption
            am.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis(), (5 * 1000), pendingIntent);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      相关资源
      最近更新 更多