0

バックグラウンド サービスを使用して 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 レイアウトを開始せずにこのアプリケーションを開始したいと考えています。サービスだけ開始して、モバイルのスタートアップで開始したいです。最後の質問です。「最後のアプリケーション リスト」からアプリケーションをスワイプすると、サービスが停止し、Bluetooth 通信が失われます。それを回避する方法はありますか?Activity を強制終了したいが、サービスは維持したい

ありがとうございました

4

1 に答える 1

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>

ブロードキャスト レシーバーを使用して、起動時または起動完了時にインテントを受信し、そこからサービスを開始します。

*) 「最後のアプリケーション リスト」からアプリケーションをスワイプすると、サービスが停止し、Bluetooth 通信が失われます。それを回避する方法はありますか?

回答: AlarmManager を使用して回避してください。非常に 5 ~ 10 秒実行されるリピート アラームを使用します。そこから、BroadCastReceiver を呼び出すことができます。そのため、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);
于 2013-10-24T15:09:32.627 に答える