학습 사용 Android 극광 메시지 푸 시

79847 단어 Android
극광 홈 페이지: www. jpush. cn 공식 안내:http://docs.jpush.io/guideline/android_guide/
SDK 다운로드
주소:http://docs.jpush.io/resources/#android- sdk 는 다운로드 할 항목 을 선택 하고 가 져 옵 니 다.
배치 하 다.
목록 파일 에 코드 를 추가 하고 가방 이름과 Appkey 를 자신의 가방 이름 으로 바 꿉 니 다.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="  "
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="14" />
    <permission
        android:name="  .permission.JPUSH_MESSAGE"
        android:protectionLevel="signature" />
    
    <uses-permission android:name="  .permission.JPUSH_MESSAGE" />
    <uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>  
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:name="  .MyApplication"
        android:theme="@style/AppTheme" >
        <activity
            android:name="  Activity"
            android:launchMode="singleTask"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            intent-filter>
        activity>

        
        <activity
            android:name="cn.jpush.android.ui.PushActivity"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:configChanges="orientation|keyboardHidden" >
            <intent-filter>
                <action android:name="cn.jpush.android.ui.PushActivity" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="  " />
            intent-filter>
        activity>
        
        <service
            android:name="cn.jpush.android.service.DownloadService"
            android:enabled="true"
            android:exported="false" >
        service>


        
        <service
            android:name="cn.jpush.android.service.PushService"
            android:enabled="true"
            android:exported="false">
            <intent-filter>
                <action android:name="cn.jpush.android.intent.REGISTER" />
                <action android:name="cn.jpush.android.intent.REPORT" />
                <action android:name="cn.jpush.android.intent.PushService" />
                <action android:name="cn.jpush.android.intent.PUSH_TIME" />

            intent-filter>
        service>

        
        <receiver
            android:name="cn.jpush.android.service.PushReceiver"
            android:enabled="true" >
            <intent-filter android:priority="1000">
                <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED_PROXY" />   
                <category android:name="  " />
            intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.USER_PRESENT" />
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            intent-filter>
             
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_ADDED" />
                <action android:name="android.intent.action.PACKAGE_REMOVED" />
                <data android:scheme="package" />
            intent-filter>

        receiver>

        
        <receiver android:name="cn.jpush.android.service.AlarmReceiver" />

        
        <receiver
            android:name="     MyReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="cn.jpush.android.intent.REGISTRATION" /> 
                <action android:name="cn.jpush.android.intent.UNREGISTRATION" />  
                <action android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" /> 
                <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" /> 
                <action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" /> 
                <action android:name="cn.jpush.android.intent.CONNECTION" />
                <action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED"/>
                <action android:name="cn.jpush.android.intent.ACTION_RICHPUSH_CALLBACK" />
                <category android:name="  " />
            intent-filter>
        receiver>


        
        <meta-data android:name="JPUSH_CHANNEL" android:value="developer-default"/>
        <meta-data android:name="JPUSH_APPKEY" android:value="XXX   AppKey XXX" /> 

    application>

manifest>

극광 푸 시 초기 화
사용자 정의 응용 프로그램
import cn.jpush.android.api.JPushInterface;
import android.app.Application;

/** 
 * @author yangshuai
 * @version     :2015-4-13   10:16:44 
 *     :   application
 */
public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        JPushInterface.setDebugMode(true);//      
        JPushInterface.init(this);//   API
    }
}

전송 정지 코드:
JPushInterface.stopPush(getApplicationContext());

복구 푸 시 코드:
JPushInterface.resumePush(getApplicationContext());

사용자 정의 Receiver 푸 시 수락
/**
 * @author yangshuai
 * @version     :2015-4-13   10:07:10 
 *     :   Receive    
 */
public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        Bundle bundle = arg1.getExtras();

        //     ,   API       title   ,Portal           
        if (bundle.containsKey(JPushInterface.EXTRA_TITLE)) {
            String titleString = bundle.getString(JPushInterface.EXTRA_TITLE);
        }

        //     ,   JSON    ,   API       extras   .
        //    Portal        “    ”      
        if (bundle.containsKey(JPushInterface.EXTRA_EXTRA)) {
            String extrasString = bundle.getString(JPushInterface.EXTRA_EXTRA);
        }

        //     ,   API       content_type   
        if (bundle.containsKey(JPushInterface.EXTRA_CONTENT_TYPE)) {
            String typeString = bundle
                    .getString(JPushInterface.EXTRA_CONTENT_TYPE);
        }

        //         ID,         。
        if (bundle.containsKey(JPushInterface.EXTRA_MSG_ID)) {
            String msgIdString = bundle.getString(JPushInterface.EXTRA_MSG_ID);
        }

        /**
         *  action     
         */
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(arg1.getAction())) {
            // SDK   JPush Server                ID ,      ID               。
            String registrationIdString = bundle
                    .getString(JPushInterface.EXTRA_REGISTRATION_ID);

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(arg1
                .getAction())) {
            System.out.println("        。     :"
                    + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            //              ,            

            //     ,   API       message   ,   Portal         "       ”  
            if (bundle.containsKey(JPushInterface.EXTRA_MESSAGE)) {
                String messageString = bundle
                        .getString(JPushInterface.EXTRA_MESSAGE);
            }
            processCustomMessage(arg0, bundle);//         

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(arg1
                .getAction())) {
            System.out.println("     ");
            //          ,        

            //      ,   API       n_title   ,   Portal         “    ”  
            String notificationTileString = bundle
                    .getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            //     ,   API       n_content   ,   Portal         “    ”  
            String alertString = bundle.getString(JPushInterface.EXTRA_ALERT);
            //     Notification ID,      Notification
            int notificationId = bundle
                    .getInt(JPushInterface.EXTRA_NOTIFICATION_ID);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(arg1
                .getAction())) {
            System.out.println("         ");
            //                      
            Toast.makeText(arg0, "      。。。。", Toast.LENGTH_SHORT).show();
            JPushInterface.reportNotificationOpened(arg0,
                    bundle.getString(JPushInterface.EXTRA_MSG_ID));//              

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(arg1
                .getAction())) {//     ,  
            boolean connected = arg1.getBooleanExtra(
                    JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            // Toast.makeText(arg0, "    " + connected,
            // Toast.LENGTH_SHORT).show();

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(arg1
                .getAction())) {
            //      

            //       Javascript   API,       ”params“
            if (bundle.containsKey(JPushInterface.EXTRA_EXTRA)) {
                String params = arg1.getStringExtra(JPushInterface.EXTRA_EXTRA);
            }

            //                     。
            if (bundle.containsKey(JPushInterface.EXTRA_RICHPUSH_FILE_PATH)) {
                String filePathString = bundle
                        .getString(JPushInterface.EXTRA_RICHPUSH_FILE_PATH);
            }

            //           HTML     ,    WebView。
            if (bundle.containsKey(JPushInterface.EXTRA_RICHPUSH_HTML_PATH)) {
                String fileHtmlPath = bundle
                        .getString(JPushInterface.EXTRA_RICHPUSH_HTML_PATH);
            }

            //                   ,       “,”   ,    fileHtmlPath
            if (bundle.containsKey(JPushInterface.EXTRA_RICHPUSH_HTML_RES)) {
                String fileImageStr = bundle
                        .getString(JPushInterface.EXTRA_RICHPUSH_HTML_RES);
                String[] fileNames = fileImageStr.split(",");
            }
        } else {
            Log.d("   action  ", "Unhandled intent - " + arg1.getAction());
        }
    }

    // send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {
        if (MainActivity.isForeground) {
            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
            msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
            if (!MyUtil.isEmpty(extras)) {
                try {
                    JSONObject extraJson = new JSONObject(extras);
                    if (null != extraJson && extraJson.length() > 0) {
                        msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
                    }
                } catch (JSONException e) {

                }

            }
            context.sendBroadcast(msgIntent);
        }
    }

    //       intent extra   
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("
key:"
+ key + ", value:" + bundle.getInt(key)); } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) { sb.append("
key:"
+ key + ", value:" + bundle.getBoolean(key)); } else { sb.append("
key:"
+ key + ", value:" + bundle.getString(key)); } } return sb.toString(); } }

주 된 사용 방법
공공 류, 모든 주요 방법 이 안에 있 습 니 다. 호출 하면 됩 니 다.
/**
 * @author yangshuai
 * @version     :2015-4-13   4:19:06     :   
 */
public class MyUtil {

    /**
     *          
     * 
     * @param context
     * @param alias
     *             null      ,"" (    )         ,  (     )、  、   、  ,      40
     *              。(       UTF-8  )
     * @param tags
     *             null      ,               ,  (     )、  、   、  ,      40
     *              ,       100   tag,        1K  。(       UTF-8  )
     * @param callback
     *              TagAliasCallback   gotResult   ,        alias,
     *            tags。         :0   
     * 
     * @              ,       。
     */
    public static void setAliasAndTags(Context context, String alias,
            Set tags, TagAliasCallback callback) {
        JPushInterface.setAliasAndTags(context, alias, tags, callback);
    }

    /**
     *     
     * 
     * @param context
     * @param alias
     *            "" (    )         ,  (     )、  、   、  
     * @param callback
     *             TagAliasCallback   gotResult   ,        alias,
     *            tags。         :0   
     * @  :           ,       。alias         40   。(       UTF-8  )
     * 
     */
    public static void setAlias(Context context, String alias,
            TagAliasCallback callback) {
        JPushInterface.setAlias(context, alias, callback);
    }

    /**
     *     
     * 
     * @param context
     * @param tags
     *                           ,  (     )、  、   、  
     * @param callback
     *              TagAliasCallback   gotResult   ,        alias,
     *            tags。         :0   
     * @  :            tag,       ,    .   tag         40   ,       100  
     *      tag,        1K  。(       UTF-8  ).           100   tag。App    tag
     *           。
     */
    public static void setTags(Context context, Set tags,
            TagAliasCallback callback) {
        JPushInterface.setTags(context, tags, callback);
    }

    /**
     *       tags
     * @param tags
     * @return     tag   。
     */
    public static Set filterValidTags(Set tags){
        return JPushInterface.filterValidTags(tags);
    }

    /**
     *       
     * 
     * @param context
     *            ApplicationContext
     * @param startHour
     *            int startHour           (24   :startHour    0 23)
     * @param endHour
     *            int endHour           (24   :endHour    0 23)
     * @param integers
     *            0     ,1     ,    。
     *            (7  ,Set     int   0 6),set   null,               
     *            ,set size 0,                .
     */
    public static void setPushTime(Context context, int startHour, int endHour,
            Integer... integers) {
        //       
        Set daysIntegers = new HashSet();
        if (integers == null) {
            daysIntegers = null;
        } else {
            for (int i = 0; i < integers.length; i++) {

                daysIntegers.add(integers[i]);
            }
        }
        JPushInterface.setPushTime(context, daysIntegers, startHour, endHour);
    }

    /**
     *          
     * 
     * @param context
     *            ApplicationContext
     * @param startHour
     *            int startHour           -    (24   ,  :0~23 )
     * @param startMinute
     *            int startMinute           -   (  :0~59 )
     * @param endHour
     *            int endHour           -    (24   ,  :0~23 )
     * @param endMinute
     *            int endMinute           -   (  :0~59 )
     */
    public static void setSilenceTime(Context context, int startHour,
            int startMinute, int endHour, int endMinute) {
        JPushInterface.setSilenceTime(context, startHour, startMinute, endHour,
                endMinute);
    }

    public static class CustomNotificationBuilder {
        private Context context;
        private int number;
        private int layoutId;
        private int iconTipId = -1;
        private int iconShowId = -1;
        private int notificationFlags = -1;
        private int notificationDefaults = 0;

        /**
         * 
         * @param context
         *            Context
         */
        public CustomNotificationBuilder(Context context) {
            super();
            this.context = context;
        }

        /**
         *     
         * 
         * @param number
         *              
         * @return
         */
        public CustomNotificationBuilder setNumber(int number) {
            this.number = number;
            return this;
        }

        /**
         *          
         * 
         * @param layoutId
         *              id
         * @return
         */
        public CustomNotificationBuilder setLayout(int layoutId) {
            this.layoutId = layoutId;
            return this;
        }

        /**
         *            
         * 
         * @param iconTipId
         *              id
         * @return
         */
        public CustomNotificationBuilder setIconTip(int iconTipId) {
            this.iconTipId = iconTipId;
            return this;
        }

        /**
         *                
         * 
         * @param iconShowId
         *              id
         * @return
         */
        public CustomNotificationBuilder setIconShow(int iconShowId) {
            this.iconShowId = iconShowId;
            return this;
        }

        /**
         *     
         * 
         * @param flags
         *               Notification.FLAG_AUTO_CANCEL;     
         * @return
         */
        public CustomNotificationBuilder setFlags(int flags) {
            this.notificationFlags = flags;
            return this;
        }

        /**
         *     ,  ,   
         * 
         * @param defaults
         *               Notification.DEFAULT_SOUND;   
         *            Notification.DEFAULT_VIBRATE ;    
         *            Notification.DEFAULT_LIGHTS
         * @return
         */
        public CustomNotificationBuilder setDefaults(int... defaults) {
            for (int i = 0; i < defaults.length; i++) {
                notificationDefaults |= defaults[i];
            }
            return this;
        }

        public void init() {
            //       Notification Layout
            CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(
                    context, layoutId, R.id.custom_push_notification_icon,
                    R.id.custom_push_notification_title,
                    R.id.custom_push_notification_text);
            if (iconTipId != -1) {
                //            
                builder.statusBarDrawable = iconTipId;
            }
            if (iconShowId != -1) {
                //                
                builder.layoutIconDrawable = iconShowId;
            }
            //     
            if (notificationFlags != -1) {
                builder.notificationFlags = notificationFlags;
            }
            //     ,  ,   。
            if (notificationDefaults != 0) {
                builder.notificationDefaults = notificationDefaults;
            }

            JPushInterface.setPushNotificationBuilder(number, builder);
        }

    }

    /**
     *       
     * 
     * @param context
     * @param number
     *              
     * @param layoutId
     *              Id
     * @param iconTipId
     *                       
     * @param iconShowId
     *                           
     * @param flags
     *                
     * @param defaults
     *                ,  ,   
     * 
     * @params flags    Notification.FLAG_AUTO_CANCEL;     
     * @params defaults    Notification.DEFAULT_SOUND;   
     *         Notification.DEFAULT_VIBRATE ;     Notification.DEFAULT_LIGHTS
     */
    public static void initCustomPushNotificationBuilder(Context context,
            int number, int layoutId, int iconTipId, int iconShowId, int flags,
            int... defaults) {
        CustomNotificationBuilder builder = new CustomNotificationBuilder(
                context);
        builder.setLayout(layoutId);
        builder.setIconTip(iconTipId);
        builder.setIconShow(iconShowId);
        builder.setNumber(number);
        builder.setFlags(flags);
        builder.setDefaults(defaults);
        builder.init();
    }

    /**
     *       
     * 
     * @param context
     * @param number
     *              
     * @param layoutId
     *              Id
     * @param iconTipId
     *                       
     * @param iconShowId
     *                           
     */
    public static void customPushNotification(Context context, int number,
            int layoutId, int iconTipId, int iconShowId) {
        //       Notification Layout
        CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(
                context, layoutId, R.id.custom_push_notification_icon,
                R.id.custom_push_notification_title,
                R.id.custom_push_notification_text);

        //            
        builder.statusBarDrawable = iconTipId;

        //                
        builder.layoutIconDrawable = iconShowId;

        JPushInterface.setPushNotificationBuilder(number, builder);
    }

    /**
     *       
     * 
     * @param context
     * @param number
     *              
     * @param layoutId
     *              Id
     */
    public static void customPushNotification(Context context, int number,
            int layoutId) {
        //       Notification Layout
        CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(
                context, layoutId, R.id.custom_push_notification_icon,
                R.id.custom_push_notification_title,
                R.id.custom_push_notification_text);

        //            
        builder.statusBarDrawable = R.drawable.ic_launcher;

        //                
        builder.layoutIconDrawable = R.drawable.ic_launcher;

        JPushInterface.setPushNotificationBuilder(number, builder);
    }

    /**
     *           
     * 
     * @param context
     * @param maxNum
     *                   
     */
    public static void setLatestNotificationNumber(Context context, int maxNum) {
        JPushInterface.setLatestNotificationNumber(context, maxNum);
    }

    /**
     *          
     * 
     * @author yangshuai
     * 
     */
    public static class localNotificationBuilder {
        private Context context;
        private JPushLocalNotification ln = new JPushLocalNotification();

        /**
         * getApplicationContext
         * 
         * @param context
         */
        public localNotificationBuilder(Context context) {
            this.context = context;
        }

        /**
         *     
         * 
         * @param number
         * @return
         */
        public localNotificationBuilder setBuilderId(long number) {
            ln.setBuilderId(number);
            return this;
        }

        /**
         *     
         * 
         * @param title
         * @return
         */
        public localNotificationBuilder setTitle(String title) {
            ln.setTitle(title);
            return this;
        }

        /**
         *     
         * 
         * @param content
         * @return
         */
        public localNotificationBuilder setContent(String content) {
            ln.setContent(content);
            return this;
        }

        /**
         *          extras json   
         * 
         * @param extras
         *            Map
         * @return
         */
        public localNotificationBuilder setExtras(Map extras) {
            JSONObject json = new JSONObject(extras);
            ln.setExtras(json.toString());
            return this;
        }

        /**
         *           
         * 
         * @param broadCastTime
         *            long
         * @return
         */
        public localNotificationBuilder setBroadcastTime(long broadCastTime) {
            ln.setBroadcastTime(broadCastTime);
            return this;
        }

        /**
         *           
         * 
         * @param date
         *            Date
         * @return
         */
        public localNotificationBuilder setBroadcastTime(Date date) {
            ln.setBroadcastTime(date);
            return this;
        }

        public localNotificationBuilder setBroadcastTime(int year, int month,
                int day, int hour, int minute, int second) {
            ln.setBroadcastTime(year, month, day, hour, minute, second);
            return this;
        }

        /**
         *        ID
         * 
         * @param notificationId
         * @return
         */
        public localNotificationBuilder setNotificationId(long notificationId) {
            ln.setNotificationId(notificationId);
            return this;
        }

        public void create() {

            JPushInterface.addLocalNotification(context, ln);
        }

    }

    /**
     *       
     * 
     * @param context
     * @param number
     * @param title
     * @param content
     * @param notificationId
     * @param time
     */
    public static void showLocalNotification(Context context, long number,
            String title, String content, long notificationId, long time) {
        MyUtil.localNotificationBuilder builder = new localNotificationBuilder(
                context);
        builder.setBuilderId(number);
        builder.setContent(content);
        builder.setTitle(title);
        builder.setNotificationId(notificationId);
        builder.setBroadcastTime(time);
        builder.create();
    }

    /**
     *        
     * 
     * @param context
     *            ApplicationContext
     */
    public static void clearAllNotifications(Context context) {
        JPushInterface.clearAllNotifications(context);
    }

    /**
     *     Id   
     * 
     * @param context
     *            ApplicationContext
     * @param notificationId
     *              ID
     */
    public static void clearNotificationById(Context context, int notificationId) {
        JPushInterface.clearNotificationById(context, notificationId);
    }

    public static final String KEY_APP_KEY = "JPUSH_APPKEY";

    public static boolean isEmpty(String s) {
        if (null == s)
            return true;
        if (s.length() == 0)
            return true;
        if (s.trim().length() == 0)
            return true;
        return false;
    }

    //   Tag Alias      ,       
    public static boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    //   AppKey
    public static String getAppKey(Context context) {
        Bundle metaData = null;
        String appKey = null;
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai)
                metaData = ai.metaData;
            if (null != metaData) {
                appKey = metaData.getString(KEY_APP_KEY);
                if ((null == appKey) || appKey.length() != 24) {
                    appKey = null;
                }
            }
        } catch (NameNotFoundException e) {

        }
        return appKey;
    }

    //      
    public static String GetVersion(Context context) {
        try {
            PackageInfo manager = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return manager.versionName;
        } catch (NameNotFoundException e) {
            return "Unknown";
        }
    }

    public static void showToast(final String toast, final Context context) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }).start();
    }

    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }
}

TagAliasCallback 오류 매개 변수 설명: 学习使用Android极光消息推送_第1张图片
부 텍스트 페이지 Javascript 리 셋 API
html 에서 다음 기능 함수 호출: 1
JPushWeb.close();//     

2
JPushWeb.startMainActivity(String params)//   Activity

HTML 에서 이 함 수 를 호출 하면 프로그램의 주 Activity 를 열 고 해당 하 는 Intent 에 인자 'params', Key 는 JPushInterface. EXTRA EXTRA 입 니 다.
Activity 에 대응 하여 params 예제 코드 가 져 오기:
Intent intent = getIntent();
if (null != intent ) {
    String params = intent.getStringExtra(JPushInterface.EXTRA_EXTRA);
}

3
JPushWeb.triggerNativeAction(String params)//  App     

HTML 에서 이 함 수 를 호출 하면 라디오 형식 으로 'params' 를 응용 프로그램 에 전달 하고 클 라 이언 트 동작 을 촉발 합 니 다. 대응 하 는 receiver:
<receiver  android:name="MyReceiver">
     ................
     <intent-filter>
    <action android:name="cn.jpush.android.intent.ACTION_RICHPUSH_CALLBACK" /> 
    <category android:name="  " />
     </intent-filter>
</receiver>

가 져 오기:
if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
        Log.d(TAG, "     RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
        //      JPushInterface.EXTRA_EXTRA           ,      Activity 、       .     
   }

html 코드 예제 참조 공식:

<html>
 <head>
  <title>JPush Webview Testtitle>
  <script>
       function clickButton() {
         JPushWeb.close();
       }

      function openUrl() {
         var json = "{'action':'open', 'url':'www.jpush.cn'}";
         JPushWeb.triggerNativeAction(json);
         JPushWeb.close(); //         json  ,       URL。
      }
 script>
 head>
 <body>
     <button onclick="javascript:clickButton(this);return false;">Closebutton>
     <button onclick="javascript:JPushWeb.startMainActivity('test - startMainActivity');return false;">StartMainActivitybutton>
     <button onclick="javascript:JPushWeb.triggerNativeAction('test - triggerNativeAction');Javascript:JPushWeb.close();">triggerNativeAction and Close current webwiewbutton>
     <button onclick="javascript:JPushWeb.startActivityByName('com.example.jpushdemo.TestActivity','test - startActivityByName');">startActivityByNamebutton>
     <button onclick="javascript:openUrl();">open a urlbutton>
 body>
html>

学习使用Android极光消息推送_第2张图片
Activity 응용 프로그램 에서 의 사용
우선 알림 표시 줄 레이아웃 R. layot. customer notitfication layot one:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/custom_push_notification_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/custom_push_notification_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#A4C638"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/custom_push_notification_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FFB6FF"
            android:textSize="20sp" />
    LinearLayout>


LinearLayout>

주 레이아웃 은 두 개의 단추 와 하나의 텍스트 상자 로 받 아들 인 사용자 정의 메 시 지 를 표시 합 니 다. 코드 를 붙 이지 않 습 니 다.
Activity 의 코드 는 주로 사용자 정의 메 시 지 를 받 고 로 컬 알림 을 보 내 며 로 컬 알림 을 잘 알 고 사용자 정의 알림 표시 줄 을 사용 합 니 다.
public class MainActivity extends Activity implements
        android.view.View.OnClickListener {

    private EditText messageTv;
    public static boolean isForeground;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyUtil.initCustomPushNotificationBuilder(this, 1,
                R.layout.customer_notitfication_layout_one,
                R.drawable.tip_icon, R.drawable.show_icon,
                Notification.FLAG_AUTO_CANCEL, Notification.DEFAULT_SOUND,
                Notification.DEFAULT_LIGHTS);//      1    

        ((Button) findViewById(R.id.local_alert_btn)).setOnClickListener(this);
        ((Button) findViewById(R.id.local_alert_clear_btn))
                .setOnClickListener(this);
        messageTv = ((EditText) findViewById(R.id.messageString));

        registerMessageReceiver();//     Receiver       
    }

    /**
     *   onResume() onPause()       API
     */
    // /
    @Override
    protected void onResume() {
        super.onResume();
        isForeground = true;
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isForeground = false;
        JPushInterface.onPause(this);
    }

    // //
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mMessageReceiver);
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
        case R.id.local_alert_btn://         ,   111111
            MyUtil.showLocalNotification(getApplicationContext(), 1, "  title",
                    "  content  ", 111111,
                    java.lang.System.currentTimeMillis() + 10);
            break;
        case R.id.local_alert_clear_btn://         
            MyUtil.clearNotificationById(getApplicationContext(), 111111);
            break;

        default:
            break;
        }
    }

    //  Receiver       
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.yunmo.mypushdemo.permission.JPUSH_MESSAGE";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(MainActivity.this, "xxxxxx", Toast.LENGTH_SHORT)
                    .show();
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "
"
); if (!MyUtil.isEmpty(extras)) { showMsg.append(KEY_EXTRAS + " : " + extras + "
"
); } setCostomMsg(showMsg.toString()); } } } private void setCostomMsg(String msg) { if (null != messageTv) { messageTv.setText(msg); Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); messageTv.setVisibility(View.VISIBLE); } } }

demo 다운로드 (도구 클래스 포함)
Android 극광 푸 시 데모 - 다운로드 채널 - CSDN. NEThttp://download.csdn.net/detail/yang786654260/8596151

좋은 웹페이지 즐겨찾기