私の Android プロジェクトでは、2 つのデバイスが互いにペアになっています。あるデバイスから Bluetooth 経由で別のデバイスにファイルを送信したいのですが、このファイルを自動または手動で受信すると、そのデバイスのアプリはこのファイルを読み取り、それに基づいて何らかのアクションを実行する必要があります。
OnCreate メソッドを持つサービスを 1 つ作成し、CONNECTION_STATE_CHANGED のブロードキャスト リスナーを 1 つ登録します。このサービスは、私のメイン アクティビティの OnCreate メソッドで開始されます。したがって、アプリがフロントエンドにない場合でも、このブロードキャスト レシーバーはファイルを読み取り、必要なアクションを実行します。まず、これは正しい方法ですか?はいの場合、その方法を教えてください。
以下は、ブロードキャストレシーバーを登録する私のサービスファイルです。このコードを実行してファイルを受信すると、Broadcast Receiver の OnReceive が呼び出されません。
package com.android;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class FileReceiver extends Service {
private static final String ACTION = "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED";
// private BroadcastReceiver BT_CONNECTION_BCAST_Receiver;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
final IntentFilter theFilter = new IntentFilter();
theFilter.addAction(ACTION);
Log.i("LocalService", "On created ");
// Registers the receiver so that your service will listen for broadcasts
this.registerReceiver(this.btReceiver_Receiver, theFilter);
}
private final BroadcastReceiver btReceiver_Receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Do whatever you need it to do when it receives the broadcast
// Example show a Toast message...
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("BT_Connection", "Inside Receiver");
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Log.i("BT_Connection", "Device Found");
}
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
{
Log.i("BT_Connection", "On BT Connection");
}
Log.i("LocalService", "On Broadcast Receiver");
showSuccessfulBroadcast();
}
};
@Override
public void onDestroy() {
super.onDestroy();
Log.i("LocalService", "On Being Destroyed!!");
// Do not forget to unregister the receiver!!!
this.unregisterReceiver(this.btReceiver_Receiver);
}
private void showSuccessfulBroadcast() {
Toast.makeText(this, "Broadcast Successful!!!", Toast.LENGTH_LONG).show();
}
}