Android集成騰訊X5以及集成極光推送,不囉嗦,直接用

一,集成騰訊X5

  1,直接在build.gradle中添加,然後sync

api 'com.tencent.tbs.tbssdk:sdk:43697'

  2,自定義一個X5WebView,集成騰訊X5的webview,直接看代碼:

public class X5WebView extends WebView {
    private BaseActivity baseActivity;
    private WebViewClient client = new WebViewClient() {
        // 防止加載網頁時調起系統瀏覽器
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    };

    public X5WebView(Context arg0) {
        super(arg0);
        setBackgroundColor(85621);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Deprecated
    public X5WebView(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);

        this.setWebViewClient(client);
        // this.setWebChromeClient(chromeClient);
        // WebStorage webStorage = WebStorage.getInstance();
        initWebViewSettings();
        this.getView().setClickable(true);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Deprecated
    private void initWebViewSettings() {
        WebSettings webSetting = this.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //設置默認的JS Object 這裏可以自定義
//        addJavascriptInterface(new JsInterface(baseActivity), "android");
    }
}

3,接下來直接佈局文件上自定義view


        <com.hengtong.biying.views.X5WebView
            android:id="@+id/wv_football_expert_detail"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

4,其餘的跟原生的webview一樣用,直接一個loadurl完事

wv = findViewById(R.id.wv);
wv.addJavascriptInterface(new JsInterface(this), "android");//這裏是需要和H5交互的,有需要則加wv("http:www.baidu.com);//添加瀏覽器地址

5,如果需要和H5交互調用原生方法,就寫一個類,跟前端溝通好,貼一個我的

public class JsInterface {
    private BaseActivity activity;

    /**
     * Instantiate the interface and set the context
     */
    public JsInterface(BaseActivity activity) {
        this.activity = activity;
    }

   @JavascriptInterface
    public void toOpenQQ(String qq) {//打開QQ
        if (qq != null) {
            //獲取剪貼板管理器:
            ClipboardManager cm = (ClipboardManager) activity.getSystemService(activity.CLIPBOARD_SERVICE);
            // 創建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", qq);
            // 將ClipData內容放到系統剪貼板裏。
            cm.setPrimaryClip(mClipData);
            TipsUtils.toastShort(activity,"複製成功,即將跳轉");
            Utils.toOpenQQ(activity, qq);
//            new AlertDialog.Builder(activity).setMessage("複製成功,即將跳轉").setNegativeButton("取消", null).setPositiveButton("確定", (dialog, which) -> Utils.toOpenQQ(activity, qq)).show();

        } else {
            TipsUtils.toastShort(activity, "複製失敗,暫無數據!");
        }
    }

    @JavascriptInterface
    public void toOpenWx(String wx) {//打開微信
        if (wx != null) {
            //獲取剪貼板管理器:
            ClipboardManager cm = (ClipboardManager) activity.getSystemService(activity.CLIPBOARD_SERVICE);
            // 創建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", wx);
            // 將ClipData內容放到系統剪貼板裏。
            cm.setPrimaryClip(mClipData);
            TipsUtils.toastShort(activity,"複製成功,即將跳轉");
            Utils.toOpenWx(activity);
//            new AlertDialog.Builder(activity).setMessage("複製成功,即將跳轉").setNegativeButton("取消", null).setPositiveButton("確定", (dialog, which) -> Utils.toOpenWx(activity)).show();
        } else {
            TipsUtils.toastShort(activity, "複製失敗,暫無數據!");
        }
    }

    @JavascriptInterface
    public void toOpenTelephoneDial(String phone) {//打開手機 撥打電話
        if (phone != null) {
            //獲取剪貼板管理器:
            ClipboardManager cm = (ClipboardManager) activity.getSystemService(activity.CLIPBOARD_SERVICE);
            // 創建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", phone);
            // 將ClipData內容放到系統剪貼板裏。
            cm.setPrimaryClip(mClipData);
            TipsUtils.toastShort(activity,"複製成功,即將跳轉");
            Utils.toOpenTelephoneDial(activity, phone);
        } else {
            TipsUtils.toastShort(activity, "複製失敗,暫無數據!");
        }

    }
}

完事!

二,集成極光推送

1,前面的註冊極光賬號以及各種配置包名之類的就不說了,直接主題,先在build.gradle裏添加依賴

 implementation 'cn.jiguang.sdk:jpush:3.5.6'  // 此處以JPush 3.5.6 版本爲例。
    implementation 'cn.jiguang.sdk:jcore:2.2.8'  // 此處以JCore 2.2.8 版本爲例。


記得參考極光的文檔使用最新版的,還要在defaultConfig裏添加配置,不要忘
  ndk {
            //選擇要添加的對應 cpu 類型的 .so 庫。
            abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a'
            // 還可以添加 'x86', 'x86_64', 'mips', 'mips64'
        }

        manifestPlaceholders = [
                JPUSH_PKGNAME : applicationId,
                JPUSH_APPKEY : "44444444444", //JPush 上註冊的包名對應的 Appkey.
                JPUSH_CHANNEL : "developer-default", //暫時填寫默認值即可.
        ]

2,在註冊文件裏添加所需要的權限以及自定義的集成極光的service和receiver

 <permission
        android:name="com.test.test.permission.JPUSH_MESSAGE"
        android:protectionLevel="signature" />

    <!-- Required -->


    <uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
    <uses-permission android:name="android.permission.INTERNET" />
    <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.MOUNT_UNMOUNT_FILESYSTEMS"
        tools:ignore="ProtectedPermissions" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />


    <!-- Optional. Required for location feature -->
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <!-- 用於開啓 debug 版本的應用在 6.0 系統上的層疊窗口權限 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <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" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.VIBRATE" />

 <service
            android:name="com.test.test.service.JPushService"
            android:enabled="true"
            android:exported="false"
            android:process=":pushcore">
            <intent-filter>
                <action android:name="cn.jiguang.user.service.action" />
            </intent-filter>
        </service>
        <service
            android:name="cn.jpush.android.service.PushService"
            android:enabled="true"
            android:exported="false"
            android:process=":pushcore">
            <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>
        <service
            android:name="cn.jpush.android.service.DaemonService"
            android:enabled="true"
            android:exported="true"
            tools:ignore="WrongManifestParent">
            <intent-filter>
                <action android:name="cn.jpush.android.intent.DaemonService" />
                <category android:name="com.nade.nadejpush" />
            </intent-filter>
        </service>
        <!-- Required since 3.0.7 -->
        <!-- 新的 tag/alias 接口結果返回需要開發者配置一個自定的廣播 -->
        <!-- 3.3.0開始所有事件將通過該類回調 -->
        <!-- 該廣播需要繼承 JPush 提供的 JPushMessageReceiver 類, 並如下新增一個 Intent-Filter -->
        <receiver
            android:name="com.test.test.receiver.JPushReceiver"
            android:enabled="true"
            android:exported="false">
            <intent-filter>
                <action android:name="cn.jpush.android.intent.RECEIVE_MESSAGE" />
                <category android:name="com.hengtong.biying" />
            </intent-filter>
        </receiver>


        <receiver
            android:name="cn.jpush.android.service.PushReceiver"
            android:enabled="true"
            tools:ignore="WrongManifestParent">
            <intent-filter android:priority="1000">
                <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED_PROXY" />
                <category android:name="com.hengtong.biying" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.USER_PRESENT" />
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
            <!-- Optional -->
            <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>

3,自定義的service和receiver類

package com.test.test.service;

import cn.jpush.android.service.JCommonService;

public class JPushService extends JCommonService {
}
package com.test.test.receiver;

import android.content.Context;
import android.util.Log;

import com.hengtong.biying.utils.TipsUtils;

import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.NotificationMessage;
import cn.jpush.android.service.JPushMessageReceiver;

public class JPushReceiver extends JPushMessageReceiver {
    @Override
    public void onMessage(Context context, CustomMessage customMessage) {
        super.onMessage(context, customMessage);
        //消息到達 可指定類型,指定操作
//        NotificationBar.showNotifiBar(context,"我是消息","我是消息內容");
        TipsUtils.toastShort(context, customMessage.toString());

        Log.d("jpush", "onMessage: " + customMessage.message + "/" + customMessage.extra);
    }


    @Override
    public void onNotifyMessageArrived(Context context, NotificationMessage notificationMessage) {
        super.onNotifyMessageArrived(context, notificationMessage);
        // 通知到達
        Log.d("jpush", "onNotifyMessageArrived: " + notificationMessage.notificationExtras);
    }


    @Override
    public void onNotifyMessageOpened(Context context, NotificationMessage notificationMessage) {
        super.onNotifyMessageOpened(context, notificationMessage);
        // 點擊通知欄消息 可指定類型,指定操作
        Log.d("jpush", "onNotifyMessageOpened: " + notificationMessage.notificationExtras);


    }


    @Override
    public void onRegister(Context context, String s) {
        super.onRegister(context, s);
        // 保存極光id
        Log.d("jpush", "onRegister: id=" + s);


    }


    @Override
    public void onConnected(Context context, boolean b) {
        super.onConnected(context, b);
        Log.d("jpush", "onConnected: " + b);
        if (b) {
            // 鏈接監聽 保存極光id
            String registrationID = JPushInterface.getRegistrationID(context.getApplicationContext());
            Log.d("jpush", "onConnected: 連接成功獲取id=" + registrationID);
        }

    }
}

4,在Application裏或者開屏頁面添加初始化事件,網上看了一些文章都推薦在開屏頁面添加初始化事件,這裏貼下我的,記得要在create裏初始化,

 JPushInterface.setDebugMode(true);
        JPushInterface.init(context);
        if (!isNotificationEnabled(this)) {
            gotoSet();//去設置開啓通知
        } else {
            //當前app允許消息通知
        }
//注意開啓通知權限
private void gotoSet() {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            // android 8.0引導
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
        } else if (Build.VERSION.SDK_INT >= 21) {
            // android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", getPackageName());
            intent.putExtra("app_uid", getApplicationInfo().uid);
        } else {
            // 其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", getPackageName(), null));
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

完事收工,極光後臺發送一個測試消息試一下吧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章