在我的 android 项目中,我的两台设备相互配对。我想通过蓝牙将文件从一台设备发送到另一台设备,当自动或手动接收到该文件时,该设备上的我的应用程序需要读取该文件并根据它执行一些操作。
我创建了一项服务,其 OnCreate 方法为 CONNECTION_STATE_CHANGED 注册了一个广播侦听器。此服务在我的主要活动的 OnCreate 方法中启动。所以即使我的应用程序不在前端,这个广播接收器也会读取文件并执行所需的操作。首先,这是正确的做法吗?如果是,请告诉我怎么做?
以下是我注册广播接收器的服务文件。当我运行此代码并接收文件时,没有调用广播接收器的 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();
}
}