Browse Source

first commit

ok 5 years ago
parent
commit
d7999b6840

+ 17 - 0
package.json

@@ -0,0 +1,17 @@
+{
+  "name": "com.renlianiot.music",
+  "version": "1.0.0",
+  "description": "alive",
+  "cordova": {
+    "id": "com.renlianiot.music",
+    "platforms": [
+      "android"
+    ]
+  },
+  "keywords": [
+    "ecosystem:cordova",
+    "cordova-android"
+  ],
+  "author": "rlian",
+  "license": "ISC"
+}

+ 37 - 0
plugin.xml

@@ -0,0 +1,37 @@
+<?xml version='1.0' encoding='utf-8'?>
+<plugin id="com.renlianiot.music" version="1.0.0" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
+	<name>RLMusicPlugin</name>
+	<js-module name="RLMusicPlugin" src="www/RLMusicPlugin.js">
+		<clobbers target="cordova.plugins.RLMusicPlugin" />
+	</js-module>
+	<platform name="android">
+		<config-file parent="/*" target="res/xml/config.xml">
+			<feature name="RLMusicPlugin">
+				<param name="android-package" value="com.renlianiot.music.RLMusicPlugin" />
+				<param name="onload" value="true" />
+			</feature>
+		</config-file>		
+		<config-file parent="/*" target="AndroidManifest.xml">
+			    <uses-permission android:name="android.permission.WAKE_LOCK" />
+		</config-file>
+
+		<config-file parent="/manifest/application" target="AndroidManifest.xml">
+			<service
+            android:name="com.renlianiot.music.PlayerMusicService"
+            android:enabled="true"
+            android:exported="true"
+            android:process=":music_service"
+            ></service>
+            <receiver android:name="com.renlianiot.music.NotificationClickReceiver">
+  			</receiver>
+		</config-file>
+		<source-file src="src/android/RLMusicPlugin.java" target-dir="src/com/renlianiot/music" />
+
+		<source-file src="src/android/PlayerMusicService.java" target-dir="src/com/renlianiot/music" />
+		<source-file src="src/android/MResource.java" target-dir="src/com/renlianiot/music" />
+		<source-file src="src/android/NotificationClickReceiver.java" target-dir="src/com/renlianiot/music" />
+		
+		<source-file src="src/res/raw/ding.mp3" target-dir="res/raw" />
+		<framework src="com.android.support:appcompat-v7:26.1.0" />
+	</platform>
+</plugin>

+ 23 - 0
src/android/MResource.java

@@ -0,0 +1,23 @@
+package com.renlianiot.music;
+public class MResource {
+	public static int getIdByName(String packageName, String className, String resName) {
+		int id = 0;
+		try {
+			Class r = Class.forName(packageName + ".R");
+			Class[] classes = r.getClasses();
+			Class desireClass = null;
+			for (Class cls : classes) {
+				if (cls.getName().split("\\$")[1].equals(className)) {
+				desireClass = cls;
+				break;
+				}
+			}
+			if (desireClass != null) {
+				id = desireClass.getField(resName).getInt(desireClass);
+			}
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return id;
+	}
+}

+ 21 - 0
src/android/NotificationClickReceiver.java

@@ -0,0 +1,21 @@
+package com.renlianiot.music;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+
+public class NotificationClickReceiver extends BroadcastReceiver {
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        if (RLMusicPlugin.CordovaActivity == null) {
+        	Log.e(RLMusicPlugin.TAG, "RLMusicPlugin.CordovaActivity null");
+        	return;
+        }
+        Log.i("TAG", "userClick:我被点击啦!!! " + intent.getStringExtra("para"));
+        Intent newIntent = new Intent(context, RLMusicPlugin.CordovaActivity.getClass()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        context.startActivity(newIntent);
+    }
+}

+ 154 - 0
src/android/PlayerMusicService.java

@@ -0,0 +1,154 @@
+package com.renlianiot.music;
+
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.app.Service;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.graphics.BitmapFactory;
+import android.media.MediaPlayer;
+import android.os.Build;
+import android.os.IBinder;
+import android.os.PowerManager;
+import android.support.annotation.Nullable;
+import android.support.v4.app.NotificationCompat;
+import android.util.Log;
+
+import java.lang.reflect.Method;
+import java.util.Timer;
+import java.util.TimerTask;
+
+public class PlayerMusicService extends Service {
+    private final static String TAG = RLMusicPlugin.TAG;
+    private MediaPlayer mMediaPlayer;
+
+
+    @Nullable
+    @Override
+    public IBinder onBind(Intent intent) {
+        return null;
+    }
+
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+        mMediaPlayer = MediaPlayer.create(getApplicationContext(), MResource.getIdByName(getApplication().getPackageName(), "raw", "ding"));
+        mMediaPlayer.setLooping(true);
+    }
+
+
+    public static final String ONCLICK = "com.app.onclick";
+
+
+    private BroadcastReceiver receiverOnclick = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (intent.getAction().equals(ONCLICK)) {
+                //Intent newIntent = new Intent(context, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+                //context.startActivity(newIntent);
+            }
+        }
+    };
+
+    public static PlayerMusicService playerMusicService = null;
+    private static void startNotification(String title, String content, String para) {
+            if (playerMusicService == null) {
+                Log.e(TAG, "playerMusicService null");
+                return;
+            }
+             Log.d(TAG, "title:" + title + " content:" + content + " para:" + para);
+            //静态注册
+            Intent intent2 =new Intent (playerMusicService.getApplicationContext(), NotificationClickReceiver.class);
+            if (para != null) {
+                intent2.putExtra("para", para);
+            }
+            PendingIntent pendingIntent = PendingIntent.getBroadcast(playerMusicService.getApplicationContext(), 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
+
+            //动态注册
+            // IntentFilter filter_click = new IntentFilter();
+            // filter_click.addAction(ONCLICK);
+            // //注册广播
+            // registerReceiver(receiverOnclick, filter_click);
+            // Intent Intent_pre = new Intent(ONCLICK);
+            // //得到PendingIntent
+            // PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, Intent_pre, 0);
+
+
+
+            NotificationManager notificationManager= (NotificationManager) playerMusicService.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
+            Notification notification=new NotificationCompat.Builder(playerMusicService.getApplicationContext())
+                    .setContentTitle(title)
+                    .setContentText(content)
+                    // .setSmallIcon(R.drawable.ic_launcher_foreground)
+                    .setSmallIcon(MResource.getIdByName(playerMusicService.getApplication().getPackageName(), "mipmap","ic_launcher"))
+                    .setWhen(System.currentTimeMillis())
+                    .setContentIntent(pendingIntent)
+                    .setAutoCancel(true)
+                    .build();
+
+            int  notifiId=1;
+    //      notificationManager.notify(notifiId,notification);
+            playerMusicService.startForeground(notifiId, notification);
+
+    }
+
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        if (playerMusicService == null) {
+            playerMusicService = this;
+        } else {
+            if (intent.getStringExtra("title") != null) {//只是修改通知栏内容
+                 startNotification(intent.getStringExtra("title"), intent.getStringExtra("content"), intent.getStringExtra("para"));
+                 return START_STICKY;
+            }
+        }
+
+
+        //playerMusicService.stopForeground(true);
+        new Thread(new Runnable() {
+            @Override
+            public void run() {
+                startPlayMusic();
+            }
+        }).start();
+
+
+        startNotification(intent.getStringExtra("title"), intent.getStringExtra("content"), intent.getStringExtra("para"));
+        return START_STICKY;
+    }
+
+
+    private void startPlayMusic(){
+        if(mMediaPlayer != null){
+
+            PowerManager pm= (PowerManager) getSystemService(Context.POWER_SERVICE);
+            PowerManager.WakeLock wl=pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "myservice");
+            wl.acquire();
+
+            mMediaPlayer.start();
+        }
+    }
+
+
+    private void stopPlayMusic(){
+        if(mMediaPlayer != null){
+            mMediaPlayer.stop();
+        }
+    }
+
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        stopPlayMusic();
+        playerMusicService = null;
+        // 重启
+        Intent intent = new Intent(getApplicationContext(),PlayerMusicService.class);
+        startService(intent);
+    }
+}

+ 54 - 0
src/android/RLMusicPlugin.java

@@ -0,0 +1,54 @@
+package com.renlianiot.music;
+
+import org.apache.cordova.CordovaPlugin;
+import org.apache.cordova.CallbackContext;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.widget.Toast;
+import android.content.Intent;
+import android.app.Activity;
+
+import android.util.Log;
+/**
+ * This class echoes a string called from JavaScript.
+ */
+public class RLMusicPlugin extends CordovaPlugin {
+    public static String TAG = "RLMusicPlugin";
+    public static Activity CordovaActivity = null;
+    @Override
+    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
+        if (CordovaActivity == null) {
+            CordovaActivity = cordova.getActivity();
+        }
+        try {
+             if (action.equals("startMusicService") || action.equals("setNotification")) {
+                Intent intent = new Intent(cordova.getActivity(), com.renlianiot.music.PlayerMusicService.class);
+                intent.putExtra("title", args.getString(0));
+                intent.putExtra("content", args.getString(1));
+                intent.putExtra("para", args.getString(2));
+                cordova.getActivity().startService(intent);
+                return true;
+            }
+            if (action.equals("coolMethod")) {
+                String message = args.getString(0);
+                this.coolMethod(message, callbackContext);
+                return true;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+
+    private void coolMethod(String message, CallbackContext callbackContext) {
+        if (message != null && message.length() > 0) {
+            Toast.makeText(cordova.getActivity(), message, Toast.LENGTH_SHORT).show();
+            callbackContext.success(message);
+        } else {
+            callbackContext.error("Expected one non-empty string argument.");
+        }
+    }
+}

BIN
src/res/raw/ding.mp3


BIN
src/res/raw/ding2.mp3


+ 13 - 0
www/RLMusicPlugin.js

@@ -0,0 +1,13 @@
+var exec = require('cordova/exec');
+
+exports.coolMethod = function (arg0, success, error) {
+    exec(success, error, 'RLMusicPlugin', 'coolMethod', [arg0]);
+};
+
+exports.startMusicService = function (title, content, para) {
+    exec(null, null, 'RLMusicPlugin', 'startMusicService', [title, content, para]);
+};
+
+exports.setNotification = function (title, content, para) {
+    exec(null, null, 'RLMusicPlugin', 'setNotification', [title, content, para]);
+};