musicList;
18 | // Sound clock
19 | private SoundClock soundClock;
20 |
21 | private boolean isPlaying;
22 |
23 | private long delay;
24 |
25 | private int numTicks;
26 |
27 | /**
28 | * Sound player
29 | *
30 | * @param manager a soundManager have a soundPool.
31 | * @param delay The number of milliseconds to delay between ticks.
32 | * @param numTicks Starts the clock running for a specific number of ticks.
33 | */
34 | public SoundPlayer(SoundManager manager,
35 | long delay,
36 | int numTicks) {
37 | this.manager = manager;
38 | this.musicList = new ArrayList<>();
39 | this.isPlaying = false;
40 | this.delay = delay;
41 | this.numTicks = numTicks;
42 | this.soundClock = new SoundClock(delay, numTicks);
43 | }
44 |
45 | /**
46 | * add a sound to player
47 | *
48 | * @param soundName soundName
49 | */
50 | public void addSound(String soundName) {
51 | if (manager.containSound(soundName)) {
52 | musicList.add(soundName);
53 | }
54 | }
55 |
56 | /**
57 | * remove a sound from player
58 | *
59 | * @param soundName soundName
60 | */
61 | public void removeSound(String soundName) {
62 | if (manager.containSound(soundName)) {
63 | musicList.remove(soundName);
64 | }
65 | }
66 |
67 | public void play() {
68 | if (!musicList.isEmpty() &&
69 | !isPlaying) {
70 | if (soundClock.getTickNumber() == 0) {
71 | // soundClock.restart();
72 | soundClock = null;
73 | soundClock = new SoundClock(delay, numTicks);
74 | soundClock.start();
75 | } else
76 | soundClock.start();
77 | isPlaying = true;
78 | }
79 | }
80 |
81 | private class SoundClock extends TimerTask {
82 | // timer
83 | private Timer timer;
84 | // Starts the clock running for a specific number of ticks.
85 | private int tickLeft;
86 |
87 | private int tickLeftSave;
88 |
89 | // The number of milliseconds to delay between ticks.
90 | private long delay;
91 |
92 | public SoundClock(long delay, int numTicks) {
93 | init();
94 | this.tickLeft = numTicks;
95 | this.tickLeftSave = numTicks;
96 | this.delay = delay;
97 | }
98 |
99 | private void init() {
100 | this.timer = new Timer();
101 | }
102 |
103 | // tick 心跳
104 | private void tick() {
105 | if (tickLeft == 0)
106 | this.stop();
107 | else {
108 | for (int i = 0; i < musicList.size(); i++) {
109 | manager.play(musicList.get(i));
110 | }
111 | if (tickLeft > 0)
112 | tickLeft--;
113 | }
114 | }
115 |
116 | @Override
117 | public void run() {
118 | tick();
119 | }
120 |
121 | public void start(int numTicks) {
122 | this.tickLeft = numTicks;
123 | this.timer.schedule(this, 0, delay);
124 | }
125 |
126 | public void start() {
127 | if (tickLeft != 0)
128 | start(tickLeft);
129 | }
130 |
131 | public void stop() {
132 | this.cancel();
133 | this.timer.cancel();
134 | isPlaying = false;
135 | }
136 |
137 | public int getTickNumber() {
138 | return tickLeft;
139 | }
140 |
141 | public void restart() {
142 | this.tickLeft = tickLeftSave;
143 | this.timer.purge();
144 | this.timer = null;
145 | init();
146 | start();
147 | }
148 | }
149 |
150 | }
151 |
--------------------------------------------------------------------------------
/engine/src/main/java/com/lfk/justweengine/Utils/webServer/WebServerService.java:
--------------------------------------------------------------------------------
1 | package com.lfk.justweengine.Utils.webServer;
2 |
3 | import android.app.Activity;
4 | import android.app.Notification;
5 | import android.app.NotificationManager;
6 | import android.app.PendingIntent;
7 | import android.app.Service;
8 | import android.content.Intent;
9 | import android.net.wifi.SupplicantState;
10 | import android.net.wifi.WifiInfo;
11 | import android.net.wifi.WifiManager;
12 | import android.os.Binder;
13 | import android.os.IBinder;
14 |
15 | import com.lfk.justweengine.R;
16 |
17 |
18 | /**
19 | * WebServerService for Android
20 | *
21 | * @author liufengkai
22 | * Created by liufengkai on 16/1/6.
23 | */
24 | public class WebServerService extends Service {
25 | // threads translate through this handler
26 | private WebServer.MessageHandler logResult;
27 | // two follows about notification
28 | private NotificationManager notificationManager;
29 | private Notification notification;
30 | private final IBinder mBinder = new LocalBinder();
31 | // socket thread object
32 | private Servers webServers;
33 | // engine context
34 | private static Activity engine;
35 | private PendingIntent contentIntent;
36 | private boolean IsRunning;
37 |
38 | @Override
39 | public void onCreate() {
40 | super.onCreate();
41 |
42 | notificationManager = (NotificationManager)
43 | getSystemService(NOTIFICATION_SERVICE);
44 |
45 | updateNotification("Open Service");
46 | }
47 |
48 | public static void init(Activity engine) {
49 | WebServerService.engine = engine;
50 | }
51 |
52 |
53 | @Override
54 | public IBinder onBind(Intent intent) {
55 | return mBinder;
56 | }
57 |
58 | /**
59 | * update notification
60 | *
61 | * @param text update message on notification
62 | */
63 | private void updateNotification(String text) {
64 | contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, engine.getClass()), 0);
65 | Notification.Builder builder = new Notification.Builder(engine)
66 | .setContentTitle("WebServer")
67 | .setContentText(text)
68 | .setContentIntent(contentIntent)
69 | .setSmallIcon(R.mipmap.ic_launcher)
70 | .setWhen(System.currentTimeMillis());
71 | notification = builder.getNotification();
72 | notificationManager.notify(0, notification);
73 | }
74 |
75 | @Override
76 | public void onDestroy() {
77 | super.onDestroy();
78 |
79 | }
80 |
81 | public class LocalBinder extends Binder {
82 | WebServerService getService() {
83 | return WebServerService.this;
84 | }
85 | }
86 |
87 | /**
88 | * start server
89 | *
90 | * @param logResult handler to translate message
91 | * @param port port in socket
92 | */
93 | public void startServer(WebServer.MessageHandler logResult, int port) {
94 | this.logResult = logResult;
95 | // running
96 | setIsRunning(true);
97 |
98 | // get WifiManager
99 | WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
100 | WifiInfo wifiInfo = wifiManager.getConnectionInfo();
101 |
102 | // set IP
103 | WebServerDefault.setWebServerIp(WebServerDefault.intToIp(wifiInfo.getIpAddress()));
104 | // if not in wifi
105 | if (wifiInfo.getSupplicantState() != SupplicantState.COMPLETED) {
106 | this.logResult.OnError("Please connect to a WIFI-network.");
107 | try {
108 | throw new Exception("Please connect to a WIFI-network.");
109 | } catch (Exception e) {
110 | e.printStackTrace();
111 | }
112 | }
113 |
114 | // Start socket thread
115 | webServers = new Servers(engine.getApplicationContext(), logResult, port);
116 | webServers.start();
117 |
118 | updateNotification("running on " +
119 | WebServerDefault.WebServerIp + ":" + port);
120 | }
121 |
122 | public void stopServer() {
123 | setIsRunning(false);
124 | if (webServers != null) {
125 | webServers.stopServer();
126 | webServers.interrupt();
127 | }
128 | }
129 |
130 | public void setIsRunning(boolean isRunning) {
131 | this.IsRunning = isRunning;
132 | }
133 |
134 | public boolean isRunning() {
135 | return IsRunning;
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/engine/src/main/java/com/lfk/justweengine/Engine/Layer/LayerEngine.java:
--------------------------------------------------------------------------------
1 | package com.lfk.justweengine.Engine.Layer;
2 |
3 | import android.graphics.Canvas;
4 | import android.graphics.PixelFormat;
5 | import android.graphics.RectF;
6 | import android.os.Bundle;
7 | import android.view.MotionEvent;
8 | import android.view.Window;
9 |
10 | import com.lfk.justweengine.Drawable.Sprite.BaseSub;
11 | import com.lfk.justweengine.Engine.Engine;
12 | import com.lfk.justweengine.Utils.logger.LogLevel;
13 | import com.lfk.justweengine.Utils.logger.Logger;
14 |
15 | /**
16 | * 使用了Layer分层的Engine
17 | *
18 | * @author liufengkai
19 | * Created by liufengkai on 16/5/5.
20 | */
21 | public abstract class LayerEngine extends Engine {
22 | protected Screen layerEngineScreen;
23 |
24 | public abstract void init();
25 |
26 | public abstract void load();
27 |
28 | public abstract void update();
29 |
30 | public abstract void touch(MotionEvent event);
31 |
32 | public abstract void collision(BaseSub baseSub);
33 |
34 | public LayerEngine() {
35 | // init logger
36 | Logger.init().logLevel(LogLevel.NONE);
37 | }
38 |
39 | public LayerEngine(boolean isOpenDebug) {
40 | this.isOpenDebug = isOpenDebug;
41 | if (!isOpenDebug) {
42 | Logger.init().logLevel(LogLevel.NONE);
43 | } else {
44 | Logger.init();
45 | }
46 | }
47 |
48 | private void Engine() {
49 | this.layerEngineScreen = new Screen(this, new Screen.ScreenListener() {
50 | @Override
51 | public void Init() {
52 | init();
53 | }
54 |
55 | @Override
56 | public void Load() {
57 | load();
58 | }
59 |
60 | @Override
61 | public void Update() {
62 | update();
63 | }
64 |
65 | @Override
66 | public void Touch(MotionEvent event) {
67 | touch(event);
68 | }
69 | });
70 | }
71 |
72 | @Override
73 | protected void onCreate(Bundle savedInstanceState) {
74 | super.onCreate(savedInstanceState);
75 |
76 | Logger.d("engine onCreate start");
77 |
78 | this.Engine();
79 | this.requestWindowFeature(Window.FEATURE_NO_TITLE);
80 | this.getWindow().setFormat(PixelFormat.TRANSLUCENT);
81 | setContentView(layerEngineScreen);
82 | layerEngineScreen.createScreen();
83 |
84 | Logger.d("engine onCreate end");
85 |
86 | }
87 |
88 | /**
89 | * engine onResume
90 | */
91 | @Override
92 | protected void onResume() {
93 | super.onResume();
94 | Logger.d("engine onResume");
95 | layerEngineScreen.restart();
96 | // need add...
97 | }
98 |
99 | /**
100 | * engine onPause
101 | */
102 | @Override
103 | protected void onPause() {
104 | super.onPause();
105 | Logger.d("engine onPause");
106 | layerEngineScreen.pause();
107 | layerEngineScreen.addPauseTime();
108 | // need add...
109 | }
110 |
111 | /**
112 | * 设定整体背景
113 | *
114 | * @param color
115 | */
116 | public void setBackgroundColor(int color) {
117 | this.layerEngineScreen.setBackgroundColor(color);
118 | }
119 |
120 | /**
121 | * set screenOrientation
122 | *
123 | * @param mode
124 | */
125 | public void setScreenOrientation(ScreenMode mode) {
126 | setRequestedOrientation(mode.value);
127 | }
128 |
129 |
130 | @Override
131 | public Canvas getCanvas() {
132 | return layerEngineScreen.getCanvas();
133 | }
134 |
135 | public Screen getScreen() {
136 | return layerEngineScreen;
137 | }
138 |
139 | @Override
140 | public void debugDraw(RectF bound) {
141 | layerEngineScreen.debugDraw(bound);
142 | }
143 |
144 | /**
145 | * 添加一层
146 | *
147 | * @param layer
148 | */
149 | public void addLayer(Layer layer) {
150 | layerEngineScreen.addLayer(layer);
151 | }
152 |
153 | /**
154 | * 在某层之上添加一层
155 | *
156 | * @param layer
157 | * @param name
158 | */
159 | public void addLayerBefore(Layer layer, String name) {
160 | layerEngineScreen.addLayerBefore(layer, name);
161 | }
162 |
163 | /**
164 | * 在某层之下添加一层
165 | *
166 | * @param layer
167 | * @param name
168 | */
169 | public void addLayerAfter(Layer layer, String name) {
170 | layerEngineScreen.addLayerAfter(layer, name);
171 | }
172 |
173 |
174 | }
175 |
--------------------------------------------------------------------------------
/engine/src/main/java/com/lfk/justweengine/Utils/tools/ImageHelper.java:
--------------------------------------------------------------------------------
1 | package com.lfk.justweengine.Utils.tools;
2 |
3 | import android.graphics.Bitmap;
4 | import android.graphics.Canvas;
5 | import android.graphics.Color;
6 | import android.graphics.ColorMatrix;
7 | import android.graphics.ColorMatrixColorFilter;
8 | import android.graphics.Paint;
9 |
10 | /**
11 | * Created by liufengkai on 15/11/10.
12 | */
13 | public class ImageHelper {
14 |
15 | /**
16 | * 设置图片的色调\饱和度\亮度
17 | *
18 | * @param bm
19 | * @param hue 色调
20 | * @param saturation 饱和度
21 | * @param lum 亮度
22 | * @return
23 | */
24 | public static Bitmap handleImageEffect(Bitmap bm,
25 | float hue,
26 | float saturation,
27 | float lum) {
28 | Bitmap bmp = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(),
29 | Bitmap.Config.ARGB_8888);
30 |
31 | Canvas canvas = new Canvas(bmp);
32 | Paint paint = new Paint();
33 |
34 | ColorMatrix hueMatrix = new ColorMatrix();
35 | hueMatrix.setRotate(0, hue);
36 | hueMatrix.setRotate(1, hue);
37 | hueMatrix.setRotate(2, hue);
38 |
39 | ColorMatrix saturationMatrix = new ColorMatrix();
40 | saturationMatrix.setSaturation(saturation);
41 |
42 | ColorMatrix lumMatrix = new ColorMatrix();
43 | lumMatrix.setScale(lum, lum, lum, 1);
44 |
45 | ColorMatrix imageMatrix = new ColorMatrix();
46 | imageMatrix.postConcat(hueMatrix);
47 | imageMatrix.postConcat(saturationMatrix);
48 | imageMatrix.postConcat(lumMatrix);
49 |
50 | paint.setColorFilter(new ColorMatrixColorFilter(imageMatrix));
51 | canvas.drawBitmap(bm, 0, 0, paint);
52 | return bmp;
53 | }
54 |
55 | public static Bitmap handleImagePixelsOldPhoto(Bitmap bm) {
56 | Bitmap bmp = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(),
57 | Bitmap.Config.ARGB_8888);
58 | int width = bm.getWidth();
59 | int height = bm.getHeight();
60 | int color = 0;
61 | int r, g, b, a, r1, g1, b1;
62 |
63 | int[] oldPx = new int[width * height];
64 | int[] newPx = new int[width * height];
65 |
66 | bm.getPixels(oldPx, 0, bm.getWidth(), 0, 0, width, height);
67 | for (int i = 0; i < width * height; i++) {
68 | color = oldPx[i];
69 | a = Color.alpha(color);
70 | r = Color.red(color);
71 | g = Color.green(color);
72 | b = Color.blue(color);
73 |
74 | r1 = (int) (0.393 * r + 0.769 * g + 0.189 * b);
75 | g1 = (int) (0.349 * r + 0.686 * g + 0.168 * b);
76 | b1 = (int) (0.272 * r + 0.534 * g + 0.131 * b);
77 |
78 | if (r1 > 255) {
79 | r1 = 255;
80 | }
81 | if (g1 > 255) {
82 | g1 = 255;
83 | }
84 | if (b1 > 255) {
85 | b1 = 255;
86 | }
87 |
88 | newPx[i] = Color.argb(a, r1, g1, b1);
89 | }
90 | bmp.setPixels(newPx, 0, width, 0, 0, width, height);
91 | return bmp;
92 | }
93 |
94 | public static Bitmap handleImagePixelsRelief(Bitmap bm) {
95 | Bitmap bmp = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(),
96 | Bitmap.Config.ARGB_8888);
97 | int width = bm.getWidth();
98 | int height = bm.getHeight();
99 | int color = 0, colorBefore = 0;
100 | int a, r, g, b;
101 | int r1, g1, b1;
102 |
103 | int[] oldPx = new int[width * height];
104 | int[] newPx = new int[width * height];
105 |
106 | bm.getPixels(oldPx, 0, bm.getWidth(), 0, 0, width, height);
107 | for (int i = 1; i < width * height; i++) {
108 | colorBefore = oldPx[i - 1];
109 | a = Color.alpha(colorBefore);
110 | r = Color.red(colorBefore);
111 | g = Color.green(colorBefore);
112 | b = Color.blue(colorBefore);
113 |
114 | color = oldPx[i];
115 | r1 = Color.red(color);
116 | g1 = Color.green(color);
117 | b1 = Color.blue(color);
118 |
119 | r = (r - r1 + 127);
120 | g = (g - g1 + 127);
121 | b = (b - b1 + 127);
122 | if (r > 255) {
123 | r = 255;
124 | }
125 | if (g > 255) {
126 | g = 255;
127 | }
128 | if (b > 255) {
129 | b = 255;
130 | }
131 | newPx[i] = Color.argb(a, r, g, b);
132 | }
133 | bmp.setPixels(newPx, 0, width, 0, 0, width, height);
134 | return bmp;
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/engine/src/main/java/com/lfk/justweengine/Drawable/Button/TextButton.java:
--------------------------------------------------------------------------------
1 | package com.lfk.justweengine.Drawable.Button;
2 |
3 | import android.graphics.Color;
4 | import android.graphics.Paint;
5 | import android.graphics.Point;
6 | import android.graphics.Rect;
7 | import android.renderscript.Float2;
8 |
9 | import com.lfk.justweengine.Engine.Engine;
10 | import com.lfk.justweengine.Utils.tools.DisplayUtils;
11 |
12 | /**
13 | * TextButton
14 | *
15 | * @author liufengkai
16 | * Created by liufengkai on 15/12/12.
17 | */
18 | public class TextButton extends BaseButton {
19 | // text color / button color
20 | private int b_text_Color, b_button_Color;
21 | // text
22 | private String b_text;
23 | // zoom in center
24 | private boolean b_zoomCenter, b_firstInit;
25 | private Paint b_textPaint;
26 | private float b_textWidth, b_singleWidth;
27 |
28 | /**
29 | * TextButton
30 | *
31 | * @param b_engine engine context
32 | * @param name textButton name
33 | */
34 | public TextButton(Engine b_engine, String name) {
35 | super(b_engine, name);
36 | init();
37 | }
38 |
39 | /**
40 | * TextButton
41 | *
42 | * @param b_engine engine context
43 | * @param b_width w
44 | * @param b_height h
45 | * @param name textButton name
46 | */
47 | public TextButton(Engine b_engine, int b_width, int b_height, String name) {
48 | super(b_engine, b_width, b_height, name);
49 | init();
50 | }
51 |
52 | private void init() {
53 | b_text = "";
54 | b_text_Color = Color.WHITE;
55 | b_button_Color = Color.TRANSPARENT;
56 | b_zoomCenter = false;
57 | b_firstInit = false;
58 | b_position = new Point(110, 110);
59 | b_scale = new Float2(1.0f, 1.0f);
60 |
61 | b_textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
62 | b_textPaint.setColor(b_text_Color);
63 | b_textPaint.setTextSize(40);
64 |
65 | paint.setColor(b_button_Color);
66 | paint.setAntiAlias(true);
67 | paint.setStyle(Paint.Style.FILL);
68 | }
69 |
70 | @Override
71 | public void draw() {
72 | e_canvas = b_engine.getCanvas();
73 | if (b_width == 0 || b_height == 0) {
74 | float[] widths = new float[1];
75 | // 获取单个汉字的宽度
76 | b_textPaint.getTextWidths("蛤", widths);
77 | b_text = b_text != null ? b_text : "";
78 | b_textWidth = widths[0] * b_text.length();
79 | b_singleWidth = widths[0];
80 | b_width = (int) (b_text.length() * widths[0] + 2 * DisplayUtils.dip2px(16));
81 | b_height = (int) (widths[0] + 2 * DisplayUtils.dip2px(8));
82 | }
83 | int x = b_position.x;
84 | int y = b_position.y;
85 | int w = (int) (b_width * b_scale.x);
86 | int h = (int) (b_height * b_scale.y);
87 | if (!b_firstInit) {
88 | b_rect = new Rect(x, y, x + w, y + h);
89 | b_firstInit = true;
90 | }
91 |
92 | if (!b_zoomCenter) {
93 | b_rect = new Rect(x, y, x + w, y + h);
94 | }
95 | e_canvas.drawRect(b_rect, paint);
96 | e_canvas.drawText(b_text, x + (b_width / 2 - b_textWidth / 2),
97 | y + (b_height / 2 + b_singleWidth / 2), b_textPaint);
98 | }
99 |
100 | @Override
101 | public void animation() {
102 | if (b_baseAnim != null && b_baseAnim.animating) {
103 | doAnimation();
104 | }
105 | }
106 |
107 | private void doAnimation() {
108 | switch (b_baseAnim.animType) {
109 | case COLOR:
110 | paint.setColor(b_baseAnim.adjustButtonBackGround(b_button_Color, b_normal));
111 | break;
112 | }
113 | }
114 |
115 | public void setZoomCenter(boolean zoomCenter) {
116 | this.b_zoomCenter = zoomCenter;
117 | }
118 |
119 | public void setTextColor(int text_Color) {
120 | this.b_text_Color = text_Color;
121 | }
122 |
123 | public void setButtonColor(int button_Color) {
124 | this.b_button_Color = button_Color;
125 | this.paint.setColor(button_Color);
126 | }
127 |
128 |
129 | @Override
130 | public void setNormal(boolean b_normal) {
131 | if (b_baseAnim != null) {
132 | this.b_baseAnim.animating = true;
133 | this.b_normal = b_normal;
134 | }
135 | }
136 |
137 | public void setAnimation(BaseButtonAnimation anim) {
138 | this.b_baseAnim = anim;
139 | }
140 |
141 | @Override
142 | public void setText(String b_text) {
143 | this.b_text = b_text;
144 | }
145 |
146 | public void setPosition(int x, int y) {
147 | this.b_position.x = x;
148 | this.b_position.y = y;
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/engine/src/main/java/com/lfk/justweengine/Utils/showLogger/LogHandler.java:
--------------------------------------------------------------------------------
1 | package com.lfk.justweengine.Utils.showLogger;
2 |
3 | import android.os.Handler;
4 | import android.os.Message;
5 | import android.os.Parcel;
6 | import android.os.Parcelable;
7 |
8 | import com.lfk.justweengine.Utils.logger.LogCat;
9 | import com.lfk.justweengine.Utils.logger.LogLevel;
10 | import com.lfk.justweengine.Utils.logger.Options;
11 |
12 | import java.io.BufferedReader;
13 | import java.io.IOException;
14 | import java.io.InputStreamReader;
15 | import java.util.concurrent.Executors;
16 | import java.util.concurrent.ScheduledExecutorService;
17 | import java.util.concurrent.TimeUnit;
18 |
19 | /**
20 | * LogPrintHandler
21 | *
22 | * Created by liufengkai on 16/4/15.
23 | */
24 | public class LogHandler {
25 |
26 | private static LogHandler mInstance = null;
27 |
28 | private static int darningTime = 3;
29 |
30 | public static final int LOGCAT = 100;
31 |
32 | private static Handler sentHandler;
33 |
34 | private ScheduledExecutorService service;
35 |
36 | public class Line implements Parcelable {
37 | String line;
38 | String lev;
39 | String time;
40 | String tag;
41 |
42 | public Line() {
43 |
44 | }
45 |
46 | protected Line(Parcel in) {
47 | line = in.readString();
48 | lev = in.readString();
49 | time = in.readString();
50 | tag = in.readString();
51 | }
52 |
53 | public final Creator CREATOR = new Creator() {
54 | @Override
55 | public Line createFromParcel(Parcel in) {
56 | return new Line(in);
57 | }
58 |
59 | @Override
60 | public Line[] newArray(int size) {
61 | return new Line[size];
62 | }
63 | };
64 |
65 | @Override
66 | public int describeContents() {
67 | return 0;
68 | }
69 |
70 | @Override
71 | public void writeToParcel(Parcel dest, int flags) {
72 | dest.writeString(line);
73 | dest.writeString(lev);
74 | dest.writeString(time);
75 | dest.writeString(tag);
76 | }
77 | }
78 |
79 |
80 | public static LogHandler getInstance() {
81 | if (mInstance == null) {
82 | synchronized (LogHandler.class) {
83 | if (mInstance == null)
84 | mInstance = new LogHandler();
85 | }
86 | }
87 | return mInstance;
88 | }
89 |
90 | private class GetLogger implements Runnable {
91 | @Override
92 | public void run() {
93 | getLogger();
94 | }
95 | }
96 |
97 | private void getLogger() {
98 | Process process = LogCat.getInstance()
99 | .options(Options.DUMP)
100 | .withTime()
101 | .recentLines(1000)
102 | .filter("", LogLevel.VERBOSE)
103 | .commit();
104 | BufferedReader bufferedReader = null;
105 | try {
106 | bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
107 | String line;
108 | while ((line = bufferedReader.readLine()) != null) {
109 | if (sentHandler != null) {
110 | Message msg = sentHandler.obtainMessage();
111 | msg.obj = getLine(line);
112 | msg.what = LOGCAT;
113 | sentHandler.sendMessage(msg);
114 | }
115 | }
116 | } catch (Exception e) {
117 | e.printStackTrace();
118 | } finally {
119 | if (bufferedReader != null) {
120 | try {
121 | bufferedReader.close();
122 | } catch (IOException e) {
123 | e.printStackTrace();
124 | }
125 | }
126 | }
127 | }
128 |
129 | private Line getLine(String line) {
130 | Line log = new Line();
131 | int tagStart = line.indexOf("/");
132 | int msgStart = line.indexOf("):");
133 | if (msgStart == -1 || tagStart == -1) {
134 | return null;
135 | }
136 | log.tag = line.substring(tagStart + 1, msgStart + 1);
137 | log.line = line.substring(msgStart + 2);
138 | log.lev = line.substring(tagStart - 1, tagStart);
139 | log.time = line.substring(0, tagStart - 2);
140 | return log;
141 | }
142 |
143 |
144 | public LogHandler() {
145 | service = Executors.newSingleThreadScheduledExecutor();
146 |
147 | service.scheduleAtFixedRate(new GetLogger(), 0, darningTime, TimeUnit.SECONDS);
148 | }
149 |
150 | public static void init(Handler handler, int time) {
151 | sentHandler = handler;
152 | darningTime = time;
153 | }
154 |
155 | }
156 |
--------------------------------------------------------------------------------
/engine/src/main/java/com/lfk/justweengine/Utils/webServer/WebServer.java:
--------------------------------------------------------------------------------
1 | package com.lfk.justweengine.Utils.webServer;
2 |
3 | import android.app.Activity;
4 | import android.content.ComponentName;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.content.ServiceConnection;
8 | import android.os.Handler;
9 | import android.os.IBinder;
10 | import android.os.Message;
11 |
12 | import com.lfk.justweengine.Utils.logger.Logger;
13 | import com.lfk.justweengine.Utils.webServer.Interface.OnLogResult;
14 | import com.lfk.justweengine.Utils.webServer.Interface.OnPermissionFile;
15 | import com.lfk.justweengine.Utils.webServer.Interface.OnWebResult;
16 |
17 | import java.io.File;
18 | import java.util.HashMap;
19 |
20 | /**
21 | * WebServer
22 | *
23 | * @author liufengkai
24 | * Created by liufengkai on 16/1/6.
25 | */
26 | public class WebServer {
27 | private Activity engine;
28 | private static HashMap webServerRule;
29 | private OnLogResult logResult;
30 | private WebServerService webServerService;
31 | private Integer webPort = null;
32 | private ServiceConnection serviceConnection;
33 | private final int ERROR = -1;
34 | private final int LOG = 1;
35 |
36 | public WebServer(Activity engine) {
37 | this.engine = engine;
38 | init();
39 | }
40 |
41 | public WebServer(Activity engine, OnLogResult logResult) {
42 | this.engine = engine;
43 | this.logResult = logResult;
44 | init();
45 | }
46 |
47 | public WebServer(Activity engine, OnLogResult logResult, int webPort) {
48 | this.engine = engine;
49 | this.logResult = logResult;
50 | this.webPort = webPort;
51 | init();
52 | }
53 |
54 | private void init() {
55 | webServerRule = new HashMap<>();
56 |
57 | WebServerService.init(engine);
58 |
59 | serviceConnection = new ServiceConnection() {
60 | @Override
61 | public void onServiceConnected(ComponentName name, IBinder service) {
62 | webServerService = ((WebServerService.LocalBinder) service).getService();
63 | if (logResult != null)
64 | logResult.OnResult(WebServerDefault.WebServerServiceConnected);
65 | }
66 |
67 | @Override
68 | public void onServiceDisconnected(ComponentName name) {
69 | webServerService = null;
70 | if (logResult != null)
71 | logResult.OnResult(WebServerDefault.WebServerServiceDisconnected);
72 | }
73 | };
74 |
75 | }
76 |
77 |
78 | public void startWebService() {
79 | if (webServerService != null) {
80 | webServerService.startServer(new MessageHandler(),
81 | (webPort == null) ? WebServerDefault.WebDefaultPort : webPort);
82 | }
83 | }
84 |
85 | public void stopWebService() {
86 | if (webServerService != null) {
87 | webServerService.stopServer();
88 | }
89 | }
90 |
91 | public void initWebService() {
92 | WebServerDefault.init(engine.getApplicationContext());
93 | // 绑定Service
94 | engine.bindService(new Intent(engine, WebServerService.class),
95 | serviceConnection,
96 | Context.BIND_AUTO_CREATE
97 | );
98 | }
99 |
100 | public void callOffWebService() {
101 | engine.unbindService(serviceConnection);
102 | }
103 |
104 | public void apply(String rule, OnWebResult result) {
105 | webServerRule.put(rule, result);
106 | }
107 |
108 | public void apply(final String rule) {
109 | webServerRule.put(rule, new OnPermissionFile() {
110 | @Override
111 | public File OnPermissionFile(String name) {
112 | Logger.e(WebServerDefault.WebServerFiles + rule + name);
113 | return new File(WebServerDefault.WebServerFiles + rule + name);
114 | }
115 | });
116 | }
117 |
118 | public static OnWebResult getRule(String rule) {
119 | return webServerRule.get(rule);
120 | }
121 |
122 | public void setLogResult(OnLogResult logResult) {
123 | this.logResult = logResult;
124 | }
125 |
126 | public class MessageHandler extends Handler {
127 | @Override
128 | public void handleMessage(Message msg) {
129 | super.handleMessage(msg);
130 | switch (msg.what) {
131 | case LOG:
132 | logResult.OnResult(msg.obj.toString());
133 | break;
134 | case ERROR:
135 | logResult.OnError(msg.obj.toString());
136 | break;
137 | }
138 | }
139 |
140 | public void OnError(String str) {
141 | Message message = this.obtainMessage();
142 | message.what = ERROR;
143 | message.obj = str;
144 | sendMessage(message);
145 | }
146 |
147 | public void OnResult(String str) {
148 | Message message = this.obtainMessage();
149 | message.what = LOG;
150 | message.obj = str;
151 | sendMessage(message);
152 | }
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/engine/src/main/java/com/lfk/justweengine/Engine/Layer/DefaultLayer.java:
--------------------------------------------------------------------------------
1 | package com.lfk.justweengine.Engine.Layer;
2 |
3 | import android.graphics.Rect;
4 | import android.graphics.RectF;
5 | import android.util.Log;
6 | import android.view.MotionEvent;
7 |
8 | import com.lfk.justweengine.Drawable.Bone.BoneGroupSprite;
9 | import com.lfk.justweengine.Drawable.Sprite.BaseSub;
10 |
11 | import java.util.concurrent.CopyOnWriteArrayList;
12 |
13 | /**
14 | * 默认实现的绘制层
15 | *
16 | * @author liufengkai
17 | * Created by liufengkai on 16/5/8.
18 | */
19 | public class DefaultLayer extends Layer {
20 | // 对象绘制组
21 | private CopyOnWriteArrayList l_sprite_group;
22 | // 对象回收组
23 | private CopyOnWriteArrayList l_sprite_recycle_group;
24 |
25 | public DefaultLayer(Screen screen, Rect layerField) {
26 | super(LayerType.Default, screen, layerField);
27 | init();
28 | }
29 |
30 | public DefaultLayer(LayerType type, Screen screen, int x, int y, int w, int h) {
31 | super(type, screen, new Rect(x, y, w, h));
32 | init();
33 | }
34 |
35 | /**
36 | * 初始化
37 | */
38 | private void init() {
39 | l_sprite_group = new CopyOnWriteArrayList<>();
40 | l_sprite_recycle_group = new CopyOnWriteArrayList<>();
41 | }
42 |
43 | @Override
44 | protected void layerUpdate() {
45 | for (BaseSub A : l_sprite_group) {
46 | if (!A.getAlive()) continue;
47 |
48 | if (!A.isCollidable()) continue;
49 |
50 | if (A.isCollided()) continue;
51 |
52 | for (BaseSub B : l_sprite_group) {
53 | if (!B.getAlive()) continue;
54 |
55 | if (!B.isCollidable()) continue;
56 |
57 | if (B.isCollided()) continue;
58 |
59 | if (A == B) continue;
60 |
61 | if (A.getIdentifier() ==
62 | B.getIdentifier())
63 | continue;
64 |
65 | if (collisionCheck(A, B)) {
66 | A.setCollided(true);
67 | A.setOffender(B);
68 | B.setCollided(true);
69 | B.setOffender(A);
70 | break;
71 | }
72 | }
73 | }
74 | }
75 |
76 | @Override
77 | protected void layerDraw() {
78 | for (BaseSub baseSub : l_sprite_group) {
79 | if (baseSub.getAlive()) {
80 | baseSub.animation();
81 | baseSub.draw();
82 | }
83 | baseSub.debugDraw();
84 | }
85 | }
86 |
87 | @Override
88 | protected void layerCollision() {
89 | // new collision
90 | for (BaseSub baseSub : l_sprite_group) {
91 | if (!baseSub.getAlive()) {
92 | l_sprite_recycle_group.add(baseSub);
93 | l_sprite_group.remove(baseSub);
94 | continue;
95 | }
96 |
97 | if (baseSub.isCollidable()) {
98 | if (baseSub.isCollided()) {
99 | // Is it a valid object ?
100 | if (baseSub.getOffender() != null) {
101 | // collision
102 | if (layerListener != null)
103 | layerListener.Collision(baseSub);
104 | // reset offender
105 | baseSub.setOffender(null);
106 | }
107 | baseSub.setCollided(false);
108 | }
109 | }
110 |
111 | baseSub.setCollided(false);
112 | }
113 |
114 | }
115 |
116 | @Override
117 | protected void layerClick(MotionEvent event) {
118 |
119 | }
120 |
121 | /**
122 | * 检测碰撞
123 | *
124 | * @param A a 物体
125 | * @param B b 物体
126 | * @return 是否碰撞
127 | */
128 | private boolean collisionCheck(BaseSub A, BaseSub B) {
129 | return RectF.intersects(A.getBounds(), B.getBounds());
130 | }
131 |
132 | /**
133 | * add BaseSub to group
134 | *
135 | * @param sprite
136 | */
137 | public void addToSpriteGroup(BaseSub sprite) {
138 | l_sprite_group.add(sprite);
139 | }
140 |
141 | /**
142 | * add boneSprite
143 | *
144 | * @param sprite
145 | */
146 | public void addToSpriteGroup(BoneGroupSprite sprite) {
147 | for (String name : sprite.getSpriteMap().keySet()) {
148 | addToSpriteGroup(sprite.getBoneSprite(name));
149 | }
150 | }
151 |
152 | /**
153 | * remove from group
154 | *
155 | * @param sprite
156 | */
157 | public void removeFromSpriteGroup(BaseSub sprite) {
158 | l_sprite_group.remove(sprite);
159 | }
160 |
161 | public void removeFromSpriteGroup(int index) {
162 | l_sprite_group.remove(index);
163 | }
164 |
165 | /**
166 | * get size
167 | *
168 | * @return size
169 | */
170 | public int getSpriteGroupSize() {
171 | return l_sprite_group.size();
172 | }
173 |
174 | public int getRecycleGroupSize() {
175 | return l_sprite_recycle_group.size();
176 | }
177 |
178 | public void addToRecycleGroup(BaseSub baseSub) {
179 | l_sprite_recycle_group.add(baseSub);
180 | }
181 |
182 | public void removeFromRecycleGroup(int index) {
183 | l_sprite_recycle_group.remove(index);
184 | }
185 |
186 | public void removeFromRecycleGroup(BaseSub baseSub) {
187 | l_sprite_recycle_group.remove(baseSub);
188 | }
189 |
190 | public boolean isRecycleGroupEmpty() {
191 | return l_sprite_recycle_group.isEmpty();
192 | }
193 |
194 | public BaseSub recycleSubFromGroup(int id) {
195 | for (BaseSub baseSub : l_sprite_recycle_group) {
196 | if (baseSub.getIdentifier() == id) {
197 | return baseSub;
198 | }
199 | }
200 | return null;
201 | }
202 |
203 |
204 | public int getTypeSizeFromRecycleGroup(int id) {
205 | int num = 0;
206 | for (BaseSub baseSub : l_sprite_recycle_group) {
207 | if (baseSub.getIdentifier() == id) {
208 | num++;
209 | }
210 | }
211 | Log.e("num" + num, "id" + id);
212 | return num;
213 | }
214 |
215 | }
216 |
--------------------------------------------------------------------------------
/engine/src/main/java/com/lfk/justweengine/Utils/webServer/RequestSolve.java:
--------------------------------------------------------------------------------
1 | package com.lfk.justweengine.Utils.webServer;
2 |
3 | import com.lfk.justweengine.Utils.webServer.Interface.OnPostData;
4 | import com.lfk.justweengine.Utils.webServer.Interface.OnWebFileResult;
5 | import com.lfk.justweengine.Utils.webServer.Interface.OnWebResult;
6 | import com.lfk.justweengine.Utils.webServer.Interface.OnWebStringResult;
7 |
8 | import java.io.BufferedInputStream;
9 | import java.io.BufferedOutputStream;
10 | import java.io.BufferedReader;
11 | import java.io.ByteArrayOutputStream;
12 | import java.io.File;
13 | import java.io.FileInputStream;
14 | import java.io.IOException;
15 | import java.io.InputStreamReader;
16 | import java.io.OutputStream;
17 | import java.net.Socket;
18 | import java.util.HashMap;
19 |
20 | /**
21 | * Solve request
22 | *
23 | * @author liufengkai
24 | * Created by liufengkai on 16/1/14.
25 | */
26 | public class RequestSolve extends Thread {
27 | private Socket client;
28 | private BufferedReader clientReader;
29 | // url in link
30 | private String url;
31 | private HashMap params;
32 | // private String urlName = "";
33 | private int type;
34 |
35 | public RequestSolve(Socket s) {
36 | super();
37 | this.client = s;
38 |
39 | }
40 |
41 | @Override
42 | public void run() {
43 | super.run();
44 | try {
45 | clientReader = new BufferedReader(
46 | new InputStreamReader(client.getInputStream(), "UTF-8"));
47 |
48 | while (true) {
49 | String s = clientReader.readLine().trim();
50 |
51 | if (s.equals("")) {
52 | break;
53 | }
54 |
55 | // Logger.e(s + '\n');
56 | Servers.getLogResult().OnResult(s);
57 |
58 | int httpHeader = s.indexOf(" HTTP/");
59 | switch (s.substring(0, 4)) {
60 | case "GET ":
61 | // get request link
62 | url = s.substring(4, httpHeader);
63 | Servers.getLogResult().OnResult("visiting" + url);
64 | break;
65 | case "POST":
66 | int last = s.indexOf('?');
67 | params = new HashMap<>();
68 | if (last > 0) {
69 | url = s.substring(5, last);
70 | getParams(s.substring(last + 1, httpHeader));
71 | } else
72 | url = s.substring(5, httpHeader);
73 | break;
74 | }
75 | }
76 | } catch (IOException e) {
77 | e.printStackTrace();
78 | Servers.getLogResult().OnError(e.getMessage());
79 | }
80 |
81 | exeResult(url);
82 | }
83 |
84 | private void exeResult(String Url) {
85 | OnWebResult result = WebServer.getRule(Url);
86 | if (result != null) {
87 | if (result instanceof OnWebStringResult) {
88 | returnString(((OnWebStringResult) result).OnResult());
89 | } else if (result instanceof OnWebFileResult) {
90 | returnFile(((OnWebFileResult) result).returnFile());
91 | } else if (result instanceof OnPostData) {
92 | returnString(((OnPostData) result).OnPostData(params));
93 | }
94 | } else {
95 | // 在新的权限管理之前,先允许所有服务器根目录下的文件访问
96 | File file = new File(WebServerDefault.WebServerFiles + Url);
97 | if (file.exists()) {
98 | returnFile(file);
99 | }
100 | }
101 | }
102 |
103 | // private void findChildFile(String Url) {
104 | // int index = Url.lastIndexOf('/');
105 | // if (index != -1) {
106 | // Log.d("index", Url.lastIndexOf('/') + "");
107 | // // 仍能逐层递减
108 | // if (index == 0) {
109 | // exeResult("/");
110 | // urlName = "/" + urlName;
111 | // return;
112 | // }
113 | //
114 | // exeResult(Url.substring(0, index));
115 | // urlName = Url.substring(index - 1) + urlName;
116 | // }
117 | // Logger.e("Url:" + Url.substring(0, Url.lastIndexOf('/')));
118 | // Logger.e("UrlName:" + Url.substring(Url.lastIndexOf('/') + 1));
119 | // }
120 |
121 | private void returnString(String str) {
122 | try {
123 | OutputStream o = client.getOutputStream();
124 | o.write(setType(getHeaderBase(), str.length(), "200 OK").getBytes());
125 | for (int i = 0;
126 | i < str.length();
127 | i++) {
128 | o.write(str.charAt(i));
129 | }
130 | o.close();
131 | client.close();
132 | } catch (IOException e) {
133 | e.printStackTrace();
134 | }
135 | }
136 |
137 | private void returnFile(File file) {
138 | if (file.exists()) {
139 | try {
140 | BufferedInputStream inputStream =
141 | new BufferedInputStream(
142 | new FileInputStream(file));
143 | BufferedOutputStream out = new BufferedOutputStream(client.getOutputStream());
144 | ByteArrayOutputStream tempOut = new ByteArrayOutputStream();
145 | byte[] buf = new byte[4096];
146 | int count;
147 | while ((count = inputStream.read(buf)) != -1) {
148 | tempOut.write(buf, 0, count);
149 | }
150 | tempOut.flush();
151 | out.write(setType(getHeaderBase(), tempOut.size(), "200 OK").getBytes());
152 | out.write(tempOut.toByteArray());
153 | out.flush();
154 | client.close();
155 | } catch (IOException e) {
156 | e.printStackTrace();
157 | }
158 | }
159 | }
160 |
161 | private void getParams(String url) {
162 | int valueFirst;
163 | for (String s : url.split("&")) {
164 | valueFirst = s.indexOf("=");
165 | params.put(s.substring(0, valueFirst),
166 | s.substring(valueFirst + 1));
167 | }
168 | }
169 |
170 | private String getHeaderBase() {
171 | return "HTTP/1.1 %code%\n" +
172 | "Server: JustWe_WebServer/0.1\n" +
173 | "Content-Length: %length%\n" +
174 | "Connection: close\n" +
175 | "Content-Type: text/html; charset=iso-8859-1\n\n";
176 | }
177 |
178 | private String setType(String str, double length, String TYPE) {
179 | str = str.replace("%code%", TYPE);
180 | str = str.replace("%length%", "" + length);
181 | return str;
182 | }
183 | }
184 |
--------------------------------------------------------------------------------
/engine/src/main/java/com/lfk/justweengine/Utils/crashHandler/CrashHandler.java:
--------------------------------------------------------------------------------
1 | package com.lfk.justweengine.Utils.crashHandler;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.app.AlarmManager;
5 | import android.app.Application;
6 | import android.app.PendingIntent;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.content.pm.PackageInfo;
10 | import android.content.pm.PackageManager;
11 | import android.os.Build;
12 | import android.util.Log;
13 |
14 | import java.io.File;
15 | import java.io.FileOutputStream;
16 | import java.io.IOException;
17 | import java.io.PrintWriter;
18 | import java.io.StringWriter;
19 | import java.io.Writer;
20 | import java.lang.reflect.Field;
21 | import java.text.DateFormat;
22 | import java.text.SimpleDateFormat;
23 | import java.util.ArrayList;
24 | import java.util.Date;
25 | import java.util.HashMap;
26 | import java.util.Map;
27 |
28 | /**
29 | * CrashHandler
30 | * Solve thread crash
31 | *
32 | * @author liufengkai
33 | * Created by liufengkai on 16/1/16.
34 | */
35 | public class CrashHandler implements Thread.UncaughtExceptionHandler {
36 | private static final String TAG = "CrashHandler";
37 |
38 | private Application context;
39 |
40 | private HashMap info;
41 |
42 | private DateFormat formatter;
43 |
44 | private static CrashHandler instance;
45 |
46 | private Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
47 |
48 | // Restart activity
49 | private Class> Activity = null;
50 |
51 | private String ActivityName = null;
52 |
53 | private ArrayList listener;
54 |
55 | /**
56 | * get CrashHandler Instance
57 | *
58 | * @return CrashHandler
59 | */
60 | public static CrashHandler getInstance() {
61 | if (instance == null) {
62 | instance = new CrashHandler();
63 | }
64 | return instance;
65 | }
66 |
67 | public void setRestartActivity(Class> activity) {
68 | this.Activity = activity;
69 | }
70 |
71 | public void setActivityName(String activityName) {
72 | ActivityName = activityName;
73 | }
74 |
75 | /**
76 | * init
77 | *
78 | * @param context
79 | */
80 | @SuppressLint("SimpleDateFormat")
81 | public void init(Application context) {
82 | this.context = context;
83 | uncaughtExceptionHandler =
84 | Thread.getDefaultUncaughtExceptionHandler();
85 | Thread.setDefaultUncaughtExceptionHandler(this);
86 |
87 | info = new HashMap<>();
88 | listener = new ArrayList<>();
89 | formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
90 |
91 | CrashHandlerDefault.init();
92 | }
93 |
94 |
95 | @Override
96 | public void uncaughtException(Thread thread, Throwable ex) {
97 | handleException(ex);
98 | uncaughtExceptionHandler
99 | .uncaughtException(thread, ex);
100 | }
101 |
102 |
103 | private boolean handleException(Throwable throwable) {
104 | if (throwable == null)
105 | return false;
106 | if (listener != null) {
107 | for (int i = 0; i < listener.size(); i++) {
108 | listener.get(i).AfterCrash();
109 | }
110 | }
111 | collectDeviceInfo(context);
112 | writeCrashInfoToFile(throwable);
113 | if (Activity != null)
114 | restart(Activity);
115 | else if (ActivityName != null) {
116 | restart(ActivityName);
117 | }
118 | return true;
119 | }
120 |
121 | /**
122 | * Collect Device Info
123 | *
124 | * @param ctx context
125 | */
126 | public void collectDeviceInfo(Context ctx) {
127 | try {
128 | PackageManager pm = ctx.getPackageManager();
129 | PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
130 | PackageManager.GET_ACTIVITIES);
131 | if (pi != null) {
132 | String versionName = pi.versionName == null ? "null"
133 | : pi.versionName;
134 | String versionCode = pi.versionCode + "";
135 | info.put("versionName", versionName);
136 | info.put("versionCode", versionCode);
137 | info.put("crashTime", formatter.format(new Date()));
138 | }
139 | } catch (PackageManager.NameNotFoundException e) {
140 | Log.e(TAG, "an error occurred when collect package info", e);
141 | }
142 | Field[] fields = Build.class.getDeclaredFields();
143 | for (Field field : fields) {
144 | try {
145 | field.setAccessible(true);
146 | info.put(field.getName(), field.get(null).toString());
147 | Log.d(TAG, field.getName() + " : " + field.get(null));
148 | } catch (Exception e) {
149 | Log.e(TAG, "an error occurred when collect crash info", e);
150 | }
151 | }
152 | }
153 |
154 | /**
155 | * Write crash info To File
156 | *
157 | * @param ex throwable message
158 | */
159 | private void writeCrashInfoToFile(Throwable ex) {
160 | StringBuilder sb = new StringBuilder();
161 | sb.append("crash log by JustWeEngine \n");
162 | for (Map.Entry entry : info.entrySet()) {
163 | sb.append(entry.getKey())
164 | .append("---------->")
165 | .append(entry.getValue())
166 | .append("\n");
167 | }
168 |
169 | Writer writer = new StringWriter();
170 | PrintWriter printWriter = new PrintWriter(writer);
171 | ex.printStackTrace(printWriter);
172 | Throwable cause = ex.getCause();
173 | while (cause != null) {
174 | cause.printStackTrace(printWriter);
175 | cause = cause.getCause();
176 | }
177 | printWriter.close();
178 | String result = writer.toString();
179 | sb.append(result);
180 | writeLog(sb.toString());
181 | }
182 |
183 | /**
184 | * write log in file
185 | *
186 | * @param log log
187 | */
188 | private void writeLog(String log) {
189 | File file = new File(CrashHandlerDefault.Log_Default_Path
190 | + "/" + formatter.format(new Date()) + ".log");
191 | try {
192 | FileOutputStream fileOutputStream = new FileOutputStream(file);
193 | byte[] bytes = log.getBytes();
194 | fileOutputStream.write(bytes);
195 | fileOutputStream.close();
196 | } catch (IOException e) {
197 | e.printStackTrace();
198 | }
199 | }
200 |
201 | /**
202 | * restart Activity
203 | *
204 | * @param activity classZ
205 | */
206 | private void restart(Class> activity) {
207 | try {
208 | Thread.sleep(1000);
209 | } catch (InterruptedException e) {
210 | Log.e(TAG, "error : ", e);
211 | }
212 | Intent intent = new Intent(context.getApplicationContext(), activity);
213 | restart(intent);
214 | }
215 |
216 |
217 | private void restart(String className) {
218 | try {
219 | Thread.sleep(1000);
220 | } catch (InterruptedException e) {
221 | Log.e(TAG, "error : ", e);
222 | }
223 | Intent intent = new Intent();
224 | intent.setClassName(context.getApplicationContext(), className);
225 | restart(intent);
226 | }
227 |
228 | private void restart(Intent intent) {
229 | PendingIntent restartIntent = PendingIntent.getActivity(
230 | context.getApplicationContext(), 0, intent,
231 | Intent.FLAG_ACTIVITY_CLEAR_TASK);
232 |
233 | // 使用PendingIntent重启
234 | AlarmManager mgr =
235 | (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
236 | mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
237 | restartIntent);
238 | }
239 |
240 | public void addCrashListener(AfterCrashListener listener) {
241 | this.listener.add(listener);
242 | }
243 | }
244 |
--------------------------------------------------------------------------------
/engine/engine.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | generateDebugSources
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
--------------------------------------------------------------------------------
/engine/src/main/java/com/lfk/justweengine/Utils/tools/SpUtils.java:
--------------------------------------------------------------------------------
1 | package com.lfk.justweengine.Utils.tools;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 |
6 | import org.json.JSONArray;
7 | import org.json.JSONException;
8 | import org.json.JSONObject;
9 |
10 | import java.lang.reflect.InvocationTargetException;
11 | import java.lang.reflect.Method;
12 | import java.util.ArrayList;
13 | import java.util.HashMap;
14 | import java.util.Iterator;
15 | import java.util.List;
16 | import java.util.Map;
17 | import java.util.Set;
18 |
19 | /**
20 | * 简化Sp存储的工具类
21 | *
22 | * @author liufengkai
23 | */
24 | public class SpUtils {
25 |
26 | public SpUtils() {
27 | /* cannot be instantiated */
28 | throw new UnsupportedOperationException("cannot be instantiated");
29 | }
30 |
31 | /**
32 | * Sp文件名
33 | */
34 | public static final String FILE_NAME = "share_data";
35 |
36 | /**
37 | * 保存数据的方法,添加具体数据类型
38 | *
39 | * @param context
40 | * @param key
41 | * @param object
42 | */
43 | public static void put(Context context, String key, Object object) {
44 |
45 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
46 | Context.MODE_PRIVATE);
47 | SharedPreferences.Editor editor = sp.edit();
48 |
49 | // 判断数据类型
50 | if (object instanceof String) {
51 | editor.putString(key, (String) object);
52 | } else if (object instanceof Integer) {
53 | editor.putInt(key, (Integer) object);
54 | } else if (object instanceof Boolean) {
55 | editor.putBoolean(key, (Boolean) object);
56 | } else if (object instanceof Float) {
57 | editor.putFloat(key, (Float) object);
58 | } else if (object instanceof Long) {
59 | editor.putLong(key, (Long) object);
60 | } else {
61 | editor.putString(key, object.toString());
62 | }
63 |
64 | SharedPreferencesCompat.apply(editor);
65 | }
66 |
67 | /**
68 | * 获取保存数据的方法,添加具体数据类型
69 | *
70 | * @param context
71 | * @param key
72 | * @param defaultObject
73 | * @return object
74 | */
75 | public static Object get(Context context, String key, Object defaultObject) {
76 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
77 | Context.MODE_PRIVATE);
78 |
79 | if (defaultObject instanceof String) {
80 | return sp.getString(key, (String) defaultObject);
81 | } else if (defaultObject instanceof Integer) {
82 | return sp.getInt(key, (Integer) defaultObject);
83 | } else if (defaultObject instanceof Boolean) {
84 | return sp.getBoolean(key, (Boolean) defaultObject);
85 | } else if (defaultObject instanceof Float) {
86 | return sp.getFloat(key, (Float) defaultObject);
87 | } else if (defaultObject instanceof Long) {
88 | return sp.getLong(key, (Long) defaultObject);
89 | }
90 |
91 | return null;
92 | }
93 |
94 | /**
95 | * 存放数组
96 | *
97 | * @param context
98 | * @param list
99 | * @param key
100 | */
101 | public static void putList(Context context, List list, String key) {
102 | JSONArray jsonArray = new JSONArray();
103 | for (int i = 0; i < list.size(); i++) {
104 | JSONObject object = new JSONObject();
105 | try {
106 | object.put(i + "", list.get(i));
107 | jsonArray.put(object);
108 | } catch (JSONException e) {
109 | e.printStackTrace();
110 | }
111 | }
112 | put(context, key, jsonArray.toString());
113 | }
114 |
115 | /**
116 | * 获取数组
117 | *
118 | * @param context
119 | * @param key
120 | * @return list
121 | */
122 |
123 | public static List getList(Context context, String key) {
124 | List list = new ArrayList();
125 | try {
126 | JSONArray jsonArray = new JSONArray((String) get(context, key, ""));
127 | for (int i = 0; i < jsonArray.length(); i++) {
128 | JSONObject object = jsonArray.getJSONObject(i);
129 | list.add(i, object.getString(i + ""));
130 | }
131 | } catch (JSONException e) {
132 | e.printStackTrace();
133 | }
134 | return list;
135 | }
136 |
137 | /**
138 | * 存入哈希表
139 | *
140 | * @param context
141 | * @param map
142 | * @param key
143 | */
144 | public static void putMap(Context context, Map, ?> map, String key) {
145 | JSONArray jsonArray = new JSONArray();
146 | Set set = map.entrySet();
147 | Iterator iterator = set.iterator();
148 | for (int i = 0; i < map.size(); i++) {
149 | Map.Entry mapEntry = (Map.Entry) iterator.next();
150 | try {
151 | JSONObject object = new JSONObject();
152 | object.put("key", mapEntry.getKey());
153 | object.put("value", mapEntry.getValue());
154 | jsonArray.put(object);
155 | } catch (JSONException e) {
156 | e.printStackTrace();
157 | }
158 | }
159 | put(context, key, jsonArray.toString());
160 | }
161 |
162 | /**
163 | * 读取哈希表
164 | *
165 | * @param context
166 | * @param key
167 | * @return map
168 | */
169 | public static Map getMap(Context context, String key) {
170 | Map map = new HashMap();
171 | try {
172 | JSONArray jsonArray = new JSONArray((String) get(context, key, ""));
173 | for (int i = 0; i < jsonArray.length(); i++) {
174 | try {
175 | JSONObject object = jsonArray.getJSONObject(i);
176 | map.put(object.getString("key"), object.getString("value"));
177 | } catch (JSONException e) {
178 | e.printStackTrace();
179 | }
180 | }
181 | } catch (JSONException e) {
182 | e.printStackTrace();
183 | }
184 | return map;
185 | }
186 |
187 | /**
188 | * 移除某个key值已经对应的值
189 | *
190 | * @param context
191 | * @param key
192 | */
193 | public static void remove(Context context, String key) {
194 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
195 | Context.MODE_PRIVATE);
196 | SharedPreferences.Editor editor = sp.edit();
197 | editor.remove(key);
198 | SharedPreferencesCompat.apply(editor);
199 | }
200 |
201 | /**
202 | * 清除所有数据
203 | *
204 | * @param context
205 | */
206 | public static void clear(Context context) {
207 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
208 | Context.MODE_PRIVATE);
209 | SharedPreferences.Editor editor = sp.edit();
210 | editor.clear();
211 | SharedPreferencesCompat.apply(editor);
212 | }
213 |
214 | /**
215 | * 查询某个key是否存在
216 | *
217 | * @param context
218 | * @param key
219 | * @return
220 | */
221 | public static boolean contains(Context context, String key) {
222 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
223 | Context.MODE_PRIVATE);
224 | return sp.contains(key);
225 | }
226 |
227 | /**
228 | * 返回所有的键值对
229 | *
230 | * @param context
231 | * @return map
232 | */
233 | public static Map getAll(Context context) {
234 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
235 | Context.MODE_PRIVATE);
236 | return sp.getAll();
237 | }
238 |
239 | /**
240 | * 解决SharedPreferencesCompat.apply方法的兼容类
241 | *
242 | * @author liufengkai
243 | */
244 | private static class SharedPreferencesCompat {
245 |
246 | private static final Method sApplyMethod = findApplyMethod();
247 |
248 | /**
249 | * 反射查找apply的方法
250 | *
251 | * @return method
252 | */
253 | @SuppressWarnings({"unchecked", "rawtypes"})
254 | private static Method findApplyMethod() {
255 | try {
256 | Class clz = SharedPreferences.Editor.class;
257 | return clz.getMethod("apply");
258 | } catch (NoSuchMethodException e) {
259 | e.printStackTrace();
260 | }
261 | return null;
262 | }
263 |
264 | /**
265 | * 如果找到则使用apply执行,否则使用commit
266 | *
267 | * @param editor
268 | */
269 | public static void apply(SharedPreferences.Editor editor) {
270 | try {
271 | if (sApplyMethod != null) {
272 | sApplyMethod.invoke(editor);
273 | return;
274 | }
275 | } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
276 | e.printStackTrace();
277 | }
278 | editor.commit();
279 | }
280 | }
281 |
282 | }
--------------------------------------------------------------------------------