蓝牙错误(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
最满意答案
我知道这似乎是一个巨大的一步,但我真的建议使用咕噜声 。 一旦你得到它,它真的很简单。
这是一个崩溃课程:
- 安装NodeJS
安装Grunt CLI(只需在控制台/终端中输入):
npm install -g grunt-cli在项目的根目录中创建一个简单的
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" } }一旦你这样做,只需键入:
npm install
到控制台(在项目的根目录)。 这将安装必要的grunt插件/依赖项(从上面的包文件)。现在,在项目的根目录中创建一个简单的
gruntfile.js
(它是一种用于您的项目的配置):module.exports = function (grunt) { grunt.initConfig({ };一旦完成,您只需要构建它。 输入控制台:
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:
- Install NodeJS
Install Grunt CLI (just enter this in console/terminal):
npm install -g grunt-cliCreate 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" } }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).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' ]);
Once that's done you just need to build it. Type in the console:
gruntor - 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 --forceYou 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 ...
-
如何使用UglifyJS在一个文件夹中缩小多个Javascript文件?(How to minify multiple Javascript files in a folder with UglifyJS?)[2023-08-25]
我知道这似乎是一个巨大的一步,但我真的建议使用咕噜声 。 一旦你得到它,它真的很简单。 这是一个崩溃课程: 安装NodeJS 安装Grunt CLI(只需在控制台/终端中输入): npm install -g grunt-cli 在项目的根目录中创建一个简单的package.json文件: { "name": "my-project-name", "version": "1.0.0", "devDependencies": { "grunt": "~0.4.2", "grunt ... -
UglifyJS内存不足(UglifyJS Running out of Memory)[2021-10-04]
这对我有用: "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 ...