首页 \ 问答 \ 蓝牙错误(Error with bluetooth)

蓝牙错误(Error with bluetooth)

我的应用程序使用蓝牙有问题。 该应用程序工作正常,除了几次,但我无法确定问题。 这是蓝牙的活动:

public class Bluetooth extends Activity implements OnItemClickListener{

public static void disconnect(){
    if (connectedThread != null) {
        connectedThread.cancel(); 
        connectedThread = null;
    }
}

public static void gethandler(Handler handler){//Bluetooth handler
    mHandler = handler;
}
static Handler mHandler = new Handler();

static ConnectedThread connectedThread;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
ArrayAdapter<String> listAdapter;
ListView listView;
static BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
IntentFilter filter;
BroadcastReceiver receiver;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth);
    init();
    if (btAdapter==null){
        Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
        finish();
    }else{
        if (!btAdapter.isEnabled()){
            turnOnBT();
        }
        getPairedDevices();
        startDiscovery();
    }

}


private void startDiscovery() {
    // TODO Auto-generated method stub
    btAdapter.cancelDiscovery();
    btAdapter.startDiscovery();
}

private void turnOnBT() {
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 1);
}

private void getPairedDevices() {
    devicesArray = btAdapter.getBondedDevices();
    if (devicesArray.size()>0){
        for(BluetoothDevice device:devicesArray){
            pairedDevices.add(device.getName());
        }
    }
}

private void init(){
    listView = (ListView)findViewById(R.id.listView);
    listView.setOnItemClickListener(this);
    listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
    listView.setAdapter(listAdapter);
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    pairedDevices = new ArrayList<String>();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    devices = new ArrayList<BluetoothDevice>(); 
    receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);
                String s = "";
                for(int a=0;a<pairedDevices.size();a++){
                    if (device.getName().equals(pairedDevices.get(a))){
                        //append
                        s = "(Paired)";
                        break;
                    }
                }
                listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());

            }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){

            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

            }else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                if (btAdapter.getState() == btAdapter.STATE_OFF){
                    turnOnBT();
                }
            }  
        }

    };

    registerReceiver(receiver, filter);
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    unregisterReceiver(receiver);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CANCELED){
        Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
        finish();
    }
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
    if (btAdapter.isDiscovering()){
        btAdapter.cancelDiscovery();
    }
    if (listAdapter.getItem(arg2).contains("(Paired)")){

        BluetoothDevice selectedDevice = devices.get(arg2);
        ConnectThread connect = new ConnectThread(selectedDevice);
        connect.start();
    }else {
        Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
    }
}

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        btAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
            //connectedThread = new ConnectedThread(mmSocket);
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
        mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

static class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
    StringBuffer sbb = new StringBuffer();
    public void run() {

        byte[] buffer;  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                try {
                    sleep(30);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                buffer = new byte[1024];
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(String income) {

        try {
            mmOutStream.write(income.getBytes());
            for(int i=0;i<income.getBytes().length;i++)
            Log.v("outStream"+Integer.toString(i),Character.toString((char)(Integer.parseInt(Byte.toString(income.getBytes()[i])))));
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

}

这是logcat:

08-04 17:54:52.859: D/AndroidRuntime(12302): Shutting down VM
08-04 17:54:52.859: W/dalvikvm(12302): threadid=1: thread exiting with uncaught exception (group=0x4161ace0)
08-04 17:54:52.869: E/AndroidRuntime(12302): FATAL EXCEPTION: main
08-04 17:54:52.869: E/AndroidRuntime(12302): Process: com.example.tut1, PID: 12302
08-04 17:54:52.869: E/AndroidRuntime(12302): java.lang.RuntimeException: Unable to pause activity {com.example.tut1/com.example.tut1.Bluetooth}: java.lang.IllegalArgumentException: Receiver not registered: com.example.tut1.Bluetooth$1@41e4a9e0
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3079)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3034)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3012)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread.access$1000(ActivityThread.java:144)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1222)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.os.Handler.dispatchMessage(Handler.java:102)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.os.Looper.loop(Looper.java:136)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread.main(ActivityThread.java:5139)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at java.lang.reflect.Method.invokeNative(Native Method)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at java.lang.reflect.Method.invoke(Method.java:515)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at dalvik.system.NativeStart.main(Native Method)
08-04 17:54:52.869: E/AndroidRuntime(12302): Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.example.tut1.Bluetooth$1@41e4a9e0
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:665)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1517)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:489)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at com.example.tut1.Bluetooth.onPause(Bluetooth.java:145)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.Activity.performPause(Activity.java:5335)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1233)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3065)
-04 17:54:52.869: E/AndroidRuntime(12302):  ... 13 more

编辑。

我注意到当Activity为“Bluetooth”时我崩溃,然后我按下后退按钮。 即使它并非总是如此。 有人能帮我吗? 谢谢。


I have a problem with an app that uses bluetooth. The app works fine except on a few occasions but I can not identify the problem. This is the activity of bluetooth:

public class Bluetooth extends Activity implements OnItemClickListener{

public static void disconnect(){
    if (connectedThread != null) {
        connectedThread.cancel(); 
        connectedThread = null;
    }
}

public static void gethandler(Handler handler){//Bluetooth handler
    mHandler = handler;
}
static Handler mHandler = new Handler();

static ConnectedThread connectedThread;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
ArrayAdapter<String> listAdapter;
ListView listView;
static BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
IntentFilter filter;
BroadcastReceiver receiver;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth);
    init();
    if (btAdapter==null){
        Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
        finish();
    }else{
        if (!btAdapter.isEnabled()){
            turnOnBT();
        }
        getPairedDevices();
        startDiscovery();
    }

}


private void startDiscovery() {
    // TODO Auto-generated method stub
    btAdapter.cancelDiscovery();
    btAdapter.startDiscovery();
}

private void turnOnBT() {
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 1);
}

private void getPairedDevices() {
    devicesArray = btAdapter.getBondedDevices();
    if (devicesArray.size()>0){
        for(BluetoothDevice device:devicesArray){
            pairedDevices.add(device.getName());
        }
    }
}

private void init(){
    listView = (ListView)findViewById(R.id.listView);
    listView.setOnItemClickListener(this);
    listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
    listView.setAdapter(listAdapter);
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    pairedDevices = new ArrayList<String>();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    devices = new ArrayList<BluetoothDevice>(); 
    receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);
                String s = "";
                for(int a=0;a<pairedDevices.size();a++){
                    if (device.getName().equals(pairedDevices.get(a))){
                        //append
                        s = "(Paired)";
                        break;
                    }
                }
                listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());

            }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){

            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

            }else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                if (btAdapter.getState() == btAdapter.STATE_OFF){
                    turnOnBT();
                }
            }  
        }

    };

    registerReceiver(receiver, filter);
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    unregisterReceiver(receiver);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CANCELED){
        Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
        finish();
    }
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
    if (btAdapter.isDiscovering()){
        btAdapter.cancelDiscovery();
    }
    if (listAdapter.getItem(arg2).contains("(Paired)")){

        BluetoothDevice selectedDevice = devices.get(arg2);
        ConnectThread connect = new ConnectThread(selectedDevice);
        connect.start();
    }else {
        Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
    }
}

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        btAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
            //connectedThread = new ConnectedThread(mmSocket);
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
        mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

static class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
    StringBuffer sbb = new StringBuffer();
    public void run() {

        byte[] buffer;  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                try {
                    sleep(30);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                buffer = new byte[1024];
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(String income) {

        try {
            mmOutStream.write(income.getBytes());
            for(int i=0;i<income.getBytes().length;i++)
            Log.v("outStream"+Integer.toString(i),Character.toString((char)(Integer.parseInt(Byte.toString(income.getBytes()[i])))));
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

}

and this is the logcat:

08-04 17:54:52.859: D/AndroidRuntime(12302): Shutting down VM
08-04 17:54:52.859: W/dalvikvm(12302): threadid=1: thread exiting with uncaught exception (group=0x4161ace0)
08-04 17:54:52.869: E/AndroidRuntime(12302): FATAL EXCEPTION: main
08-04 17:54:52.869: E/AndroidRuntime(12302): Process: com.example.tut1, PID: 12302
08-04 17:54:52.869: E/AndroidRuntime(12302): java.lang.RuntimeException: Unable to pause activity {com.example.tut1/com.example.tut1.Bluetooth}: java.lang.IllegalArgumentException: Receiver not registered: com.example.tut1.Bluetooth$1@41e4a9e0
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3079)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3034)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3012)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread.access$1000(ActivityThread.java:144)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1222)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.os.Handler.dispatchMessage(Handler.java:102)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.os.Looper.loop(Looper.java:136)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread.main(ActivityThread.java:5139)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at java.lang.reflect.Method.invokeNative(Native Method)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at java.lang.reflect.Method.invoke(Method.java:515)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at dalvik.system.NativeStart.main(Native Method)
08-04 17:54:52.869: E/AndroidRuntime(12302): Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.example.tut1.Bluetooth$1@41e4a9e0
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:665)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1517)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:489)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at com.example.tut1.Bluetooth.onPause(Bluetooth.java:145)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.Activity.performPause(Activity.java:5335)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1233)
08-04 17:54:52.869: E/AndroidRuntime(12302):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3065)
-04 17:54:52.869: E/AndroidRuntime(12302):  ... 13 more

EDIT.

I have noticed that crashes when the Activity is "Bluetooth" and I press the back button. Even if it does not always. can someone help me? Thank you.


原文:https://stackoverflow.com/questions/25122905
更新时间:2023-02-17 09:02

最满意答案

我知道这似乎是一个巨大的一步,但我真的建议使用咕噜声 。 一旦你得到它,它真的很简单。

这是一个崩溃课程:

  1. 安装NodeJS
  2. 安装Grunt CLI(只需在控制台/终端中输入):

    npm install -g grunt-cli
    
  3. 在项目的根目录中创建一个简单的package.json文件:

    {
      "name": "my-project-name",
      "version": "1.0.0",
      "devDependencies": {
        "grunt": "~0.4.2",
        "grunt-contrib-uglify": "~0.2.4",
        "grunt-contrib-watch" : "~0.5.3"
      }
    }
    
  4. 一旦你这样做,只需键入: npm install到控制台(在项目的根目录)。 这将安装必要的grunt插件/依赖项(从上面的包文件)。

  5. 现在,在项目的根目录中创建一个简单的gruntfile.js (它是一种用于您的项目的配置):

    module.exports = function (grunt) {
        grunt.initConfig({
    
    
    
    };
    
  6. 一旦完成,您只需要构建它。 输入控制台:

    grunt
    

    或者 - 更好 - 如果您键入执行下面的命令 - grunt将监视您的源文件的更改,如果您更改任何 - 它将自动构建它们:

    grunt watch --force
    

然后,您可以添加更多的插件,如:css minification,css preprocessors(less,sass,stylus),jshint等


I know it might seem like a huge step but I would really recommend using grunt. It's really simple once you get the hang of it.

Here's a crash course:

  1. Install NodeJS
  2. Install Grunt CLI (just enter this in console/terminal):

    npm install -g grunt-cli
    
  3. Create a simple package.json file in the root of your project:

    {
      "name": "my-project-name",
      "version": "1.0.0",
      "devDependencies": {
        "grunt": "~0.4.2",
        "grunt-contrib-uglify": "~0.2.4",
        "grunt-contrib-watch" : "~0.5.3"
      }
    }
    
  4. Once you have that, just type: npm install to the console (in the root of your project). This will install the necessary grunt plugins/dependencies (from the package file above).

  5. Now create a simple gruntfile.js in the root of your project (it's a kind of config for your project):

    module.exports = function (grunt) {
        grunt.initConfig({
    
    
        // define source files and their destinations
        uglify: {
            files: { 
                src: 'js/*.js',  // source files mask
                dest: 'jsm/',    // destination folder
                expand: true,    // allow dynamic building
                flatten: true,   // remove all unnecessary nesting
                ext: '.min.js'   // replace .js to .min.js
            }
        },
        watch: {
            js:  { files: 'js/*.js', tasks: [ 'uglify' ] },
        }
    });
    
    // load plugins
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    
    // register at least this one task
    grunt.registerTask('default', [ 'uglify' ]);
    
    };
  6. Once that's done you just need to build it. Type in the console:

    grunt
    

    or - better - if you type execute the command below - grunt will monitor your source files for changes, and if you change any of them - it will build them automatically:

    grunt watch --force
    

You can then add more plugins, like: css minification, css preprocessors (less, sass, stylus), jshint, etc.

相关问答

更多
  • 其实你想做的事情(欺骗它认为它只有1个文件)只是猫 Linux的 cat file1.js file2.js file3.js file4.js | uglifyjs -o files.min.js Windows (未测试) type file1.js file2.js > uglifyjs -o files.min.js 要么 type file1.js file2.js > merged.files.js uglifyjs -o merged.files.js Actually what you ...
  • 你要找的东西不存在。 在PHP文件中使用内联JavaScript的唯一真正原因是因为您需要插入PHP和JavaScript以动态生成部分或全部脚本。 在实际处理PHP 之前 ,您无法可靠地缩小此类JavaScript,因此在每次请求运行PHP 之后 ,您都会考虑缩小它。 这应该没什么价值,因为你的大量JavaScript不应该写在你的PHP文件中。 What you're looking for does not exist. The only real reason to have inline Java ...
  • 我知道这似乎是一个巨大的一步,但我真的建议使用咕噜声 。 一旦你得到它,它真的很简单。 这是一个崩溃课程: 安装NodeJS 安装Grunt CLI(只需在控制台/终端中输入): npm install -g grunt-cli 在项目的根目录中创建一个简单的package.json文件: { "name": "my-project-name", "version": "1.0.0", "devDependencies": { "grunt": "~0.4.2", "grunt ...
  • 这对我有用: "scripts": { "ugly": "node --max_old_space_size=4096 ./node_modules/uglify-js/bin/uglifyjs ffmpeg.js -c -o ffmpeg.min.js" }, This worked for me: "scripts": { "ugly": "node --max_old_space_size=4096 ./node_modules/uglify-js/bin/uglifyjs ff ...
  • 我使用了https://github.com/guard/guard-jammit 。 我需要添加一个config/assets.yml文件: embed_assets: on javascripts: plugins: - js-unprocessed/plugins/*.js 然后将其添加到我的Guardfile guard :jammit, :output_folder => "assets/" do watch(%r{^js-unprocessed/plugins/(.*)\. ...
  • 如果你不是在UglifyJS上死心塌地的,你可以用普通的JavaScript来解决这个问题,因为JSON不可能真的被这么多人迷惑。 要删除所有空格,请使用: JSON.stringify(JSON.parse(listOfAllFiles[i])) (假设listOfAllFiles[i]是JSON字符串。) If you're not dead set on UglifyJS, you could solve this with plain JavaScript, because JSON can't ...
  • API minify(code)而不是minify(file paths) uglifyjs.minify(fs.readFileSync('geolocation.service.js', 'utf8')) The API is minify(code) not minify(file paths) uglifyjs.minify(fs.readFileSync('geolocation.service.js', 'utf8'))
  • 前往http://lisperator.net/uglifyjs/ 一旦为NodeJS安装了它,UglifyJS2就为浏览器提供了一种快速构建方式: uglifyjs --self -c -m -o ./tmp/uglifyjs.js 这个命令对我有用。 现在,您可以立即在浏览器中使用它。 要指定方法的选项,您应该查看: http://lisperator.net/uglifyjs/codegen http://lisperator.net/uglifyjs/compress http://lispera ...
  • 关于文件监视器的几点说明: 文件监视器主要用于在保存时对文件执行一些外部操作。 为每个修改的文件调用文件观察器。 如果你想使用File Watcher一次处理多个文件(例如:将2+文件合并为1),那么你需要对所有参与文件进行硬编码(而不是使用当前文件宏$FileName$ ),除非,当然,uglify支持文件掩码(例如/path/to/folder/*.js )。 如果从目标列表中修改2个文件,则会为每个文件调用File Watcher,因此即使使用硬编码文件名,也会执行两次(相同的作业完成两次)。 考虑到 ...
  • 您指定了-o选项但未提供值。 来自文档 : -o filename或--output filename - 将结果放在filename中。 如果没有给出,结果将转到标准输出(或参见下一个)。 所以要么这样做 uglifyjs ... -o deploy/assets/js/script.min.js 或省略-o并重定向标准输出 uglifyjs ... > deploy/assets/js/script.min.js You specified the -o option but you didn't ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)