Java 广播管理器未在片段中工作

Java 广播管理器未在片段中工作,java,android,android-fragments,android-fragmentactivity,Java,Android,Android Fragments,Android Fragmentactivity,我有一个广播接收器,用于接收来自可编程设备的数据。相同的代码在活动中工作正常,但在片段中却不正常 代码如下: public class HomeFragment extends Fragment implements LocationListener { Session session; TextView textViewName; TextView textViewSteps; TextView textViewCalories; TextVi

我有一个广播接收器,用于接收来自可编程设备的数据。相同的代码在活动中工作正常,但在片段中却不正常

代码如下:

    public class HomeFragment extends Fragment implements LocationListener {

    Session session;
    TextView textViewName;
    TextView textViewSteps;
    TextView textViewCalories;
    TextView textViewDistance;
    TextView textViewFimos;
    ImageView imageViewInfo;
    public static final String TAG = "StepCounter";

    private UARTService mService = null;
    private BluetoothDevice evolutionDevice = null;

    private static final int UART_PROFILE_CONNECTED = 20;
    private static final int UART_PROFILE_DISCONNECTED = 21;
    private int mState = UART_PROFILE_DISCONNECTED;

    MyDatabase myDatabase;
    LocationManager service;
    private LocationManager locationManager;
    private String provider;
    double latitude, longitude;
    List<Byte> listBytes = new ArrayList<>();
    int rowNumber = 1;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        init(view);

        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        service_init();
    }

    private void init(View view) {

        session = new Session(getActivity());

        myDatabase = new MyDatabase(getActivity());

        service = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (!enabled) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }

        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            onLocationChanged(location);
        }


        textViewName = view.findViewById(R.id.textViewName);
        textViewSteps = view.findViewById(R.id.textViewSteps);
        textViewCalories = view.findViewById(R.id.textViewCalories);
        textViewDistance = view.findViewById(R.id.textViewDistance);
        textViewFimos = view.findViewById(R.id.textViewFimos);
        imageViewInfo = view.findViewById(R.id.imageViewInfo);

        try {
            textViewName.setText("Hi, " + session.getUser().getUser().getName());
        } catch (Exception e) {

        }

    }

    private void service_init() {
        System.out.println("---->>>>");
        Intent bindIntent = new Intent(getActivity().getApplicationContext(), UARTService.class);
        getActivity().bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);

        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
            mService = ((UARTService.LocalBinder) rawBinder).getService();
            Log.d(TAG, "onServiceConnected mService= " + mService);
            if (!mService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                getActivity().finish();
            }

        }

        public void onServiceDisconnected(ComponentName classname) {
            mService = null;
        }
    };

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UARTService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(UARTService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(UARTService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(UARTService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(UARTService.DEVICE_DOES_NOT_SUPPORT_UART);
        return intentFilter;
    }

    private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            final Intent mIntent = intent;
            //*********************//
            if (action.equals(UARTService.ACTION_GATT_CONNECTED)) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        System.out.println("------- Device Connected: " + evolutionDevice.getName() + " - " + evolutionDevice.getAddress());
                        mState = UART_PROFILE_CONNECTED;
                    }
                });
            }

            //*********************//
            if (action.equals(UARTService.ACTION_GATT_DISCONNECTED)) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        System.out.println("------- Device Disconnected");
                        mState = UART_PROFILE_DISCONNECTED;
                        mService.close();
                        evolutionDevice = null;
                    }
                });
            }

            //*********************//
            if (action.equals(UARTService.ACTION_GATT_SERVICES_DISCOVERED)) {
                mService.enableTXNotification();
            }
            //*********************//
            if (action.equals(UARTService.ACTION_DATA_AVAILABLE)) {
                final byte[] txValue = intent.getByteArrayExtra(UARTService.EXTRA_DATA);
                List<Byte> byteList = Bytes.asList(txValue);
                combineArrays(byteList);
            }
            //*********************//
            if (action.equals(UARTService.DEVICE_DOES_NOT_SUPPORT_UART)) {
                System.out.println("------- Device doesn't support UART. Disconnecting");
                mService.disconnect();
            }


        }
    };

    @Override
    public void onResume() {
        super.onResume();

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(provider, 400, 1, this);
        Log.d(TAG, "onResume");
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy()");

        try {
            LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(UARTStatusChangeReceiver);
        } catch (Exception ignore) {
            Log.e(TAG, ignore.toString());
        }
        getActivity().unbindService(mServiceConnection);
        mService.stopSelf();
        mService = null;

    }
公共类HomeFragment扩展片段实现LocationListener{
会议;
TextView textViewName;
TextView TextView步骤;
文本视图文本视图;
TextView textViewDistance;
文本视图文本视图FIMOS;
ImageView imageViewInfo;
公共静态最终字符串TAG=“StepCounter”;
专用UARTService mService=null;
私有BluetoothDevice evolutionDevice=null;
专用静态最终接口配置文件连接=20;
专用静态最终接口配置文件断开连接=21;
private int mState=UART\u PROFILE\u已断开连接;
我的数据库我的数据库;
位置管理服务;
私人场所经理场所经理;
私有字符串提供者;
双纬度,经度;
List listBytes=new ArrayList();
int rowNumber=1;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
//TODO自动生成的方法存根
视图=充气机。充气(R.layout.fragment\u home,container,false);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT\u输入\状态\始终\隐藏);
初始(视图);
返回视图;
}
@凌驾
创建时的公共void(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
服务初始化();
}
私有void init(视图){
会话=新会话(getActivity());
myDatabase=新建myDatabase(getActivity());
服务=(LocationManager)getActivity().getSystemService(Context.LOCATION\u服务);
布尔启用=服务.isProviderEnabled(LocationManager.GPS\U提供程序);
如果(!已启用){
意向意向=新意向(设置、动作、位置、来源、设置);
星触觉(意向);
}
locationManager=(locationManager)getActivity().getSystemService(Context.LOCATION\u服务);
标准=新标准();
provider=locationManager.getBestProvider(条件,false);
if(ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予和&ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS\u LOCATION)!=PackageManager.permission\u已授予){
考虑到呼叫
//ActivityCompat#请求权限
//在此处请求缺少的权限,然后覆盖
//public void onRequestPermissionsResult(int-requestCode,字符串[]权限,
//int[]格兰特结果)
//处理用户授予权限的情况。请参阅文档
//对于ActivityCompat,请请求权限以获取更多详细信息。
返回;
}
Location Location=locationManager.getLastKnownLocation(提供者);
//初始化位置字段
如果(位置!=null){
System.out.println(“已选择提供程序”+提供程序+”);
onLocationChanged(位置);
}
textViewName=view.findViewById(R.id.textViewName);
textViewSteps=view.findViewById(R.id.textViewSteps);
textViewCarries=view.findViewById(R.id.textViewCarries);
textViewDistance=view.findViewById(R.id.textViewDistance);
textViewFimos=view.findViewById(R.id.textViewFimos);
imageViewInfo=view.findViewById(R.id.imageViewInfo);
试一试{
textViewName.setText(“嗨,”+session.getUser().getUser().getName());
}捕获(例外e){
}
}
私有void服务_init(){
System.out.println(“--->>>”);
Intent bindIntent=新的Intent(getActivity().getApplicationContext(),UARTService.class);
getActivity().bindService(bindIntent、mServiceConnection、Context.BIND\u AUTO\u CREATE);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(UARTStatusChangeReceiver,makeGattUpdateIntentFilter());
}
专用ServiceConnection mServiceConnection=新ServiceConnection(){
服务连接上的公共void(组件名称类名称,IBinder rawBinder){
mService=((UARTService.LocalBinder)rawBinder).getService();
Log.d(标签,“onServiceConnected mService=“+mService”);
如果(!mService.initialize()){
Log.e(标记“无法初始化蓝牙”);
getActivity().finish();
}
}
ServiceDisconnected上的公共void(ComponentName类名称){
mService=null;
}
};
私有静态IntentFilter makeGattUpdateIntentFilter(){
final IntentFilter IntentFilter=新IntentFilter();
intentFilter.addAction(UARTService.ACTION\u GATT\u已连接);
intentFilter.addAction(UARTService.ACTION\u GATT\u断开);
intentFilter.addAction(UARTService.ACTION\u GATT\u SERVICES\u DISCOVERED);
intentFilter.addAction(UARTService.ACTION\u数据可用);
intentFilter.addAction(UARTService.DEVICE不支持UART);
返回意向过滤器;
}
专用最终广播接收器UARTStatusChangeReceiver=新广播接收器(){
公共void onReceive(上下文、意图){
String action=intent.getAction();
最终意图MINENT=意图;
//*********************//
if(动作等于(UARTService动作与GATT连接)){
getActivity().runOnUiThread(新的Runnable()){
公开募捐{
System.out.println(“----设备连接:”+evolutionDevice.getName()+“-”+evolutionDevice.getAd
getActivity().registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
getActivity().unregisterReceiver(UARTStatusChangeReceiver);
public class BroadcastHelper {
    public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
    public static final String ACTION_NAME = "hossam";

    public static void sendInform(Context context, String method) {
        Intent intent = new Intent();
        intent.setAction(ACTION_NAME);
        intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
        try {
            context.sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void sendInform(Context context, String method, Intent intent) {
        intent.setAction(ACTION_NAME);
        intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
        try {
            context.sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
private Receiver receiver;
private boolean isReciverRegistered = false;


@Override
public void onResume() {
    super.onResume();
    if (receiver == null) {
        receiver = new Receiver();
        IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
        getActivity().registerReceiver(receiver, filter);
        isReciverRegistered = true;
    }
}

@Override
public void onDestroy() {
    if (isReciverRegistered) {
        if (receiver != null)
            getActivity().unregisterReceiver(receiver);
    }
    super.onDestroy();
}

private class Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
        String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
        if (methodName != null && methodName.length() > 0) {
            Log.v("receive", methodName);
            switch (methodName) {

                case "Test":
                    Toast.makeText(getActivity(), "message", Toast.LENGTH_SHORT).show();
                    break;

                default:
                    break;

            }
        }
    }
}
BroadcastHelper.sendInform(context, "Test");
Intent intent = new Intent("intent");
intent.putExtra("desc", desc);
intent.putExtra("name", Local_name);
intent.putExtra("code", productCode);
BroadcastHelper.sendInform(getActivity(), "Test" , intent);