Skip to content

Commit

Permalink
Andriod版Demo增加前台服务,提升保活能力
Browse files Browse the repository at this point in the history
  • Loading branch information
Jack Jiang committed Oct 15, 2020
1 parent ac2da05 commit 709d7fa
Show file tree
Hide file tree
Showing 14 changed files with 434 additions and 16 deletions.
Binary file modified demo_binary/TCP_Client/MobileIMSDKDemo-Android(TCP).apk
Binary file not shown.
Binary file modified demo_binary/UDP_Client/MobileIMSDKDemo-Andriod(UDP).apk
Binary file not shown.
Binary file not shown.
2 changes: 1 addition & 1 deletion demo_src/TCP_Client/MobileIMSDK4aDemo_tcp/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ android {
minSdkVersion 14
targetSdkVersion 29
versionCode 104
versionName "v5.0b200917.1"
versionName "v5.0b201015.3"
//testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- Android 9.0中需要此权限的添加,不然崩溃 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<application
android:allowBackup="true"
Expand All @@ -13,7 +15,7 @@
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name="net.x52im.mobileimsdk.android.demo.SplashScreenActivity"
android:name=".SplashScreenActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppThemeBlackBar"
Expand All @@ -25,21 +27,24 @@
</intent-filter>
</activity>
<activity
android:name="net.x52im.mobileimsdk.android.demo.LoginActivity"
android:name=".LoginActivity"
android:configChanges="screenSize|keyboardHidden|orientation"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity"
android:theme="@style/AppTheme"
android:windowSoftInputMode="adjustUnspecified|stateHidden" >
</activity>
<activity
android:name="net.x52im.mobileimsdk.android.demo.MainActivity"
android:name=".MainActivity"
android:configChanges="screenSize|keyboardHidden|orientation"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity"
android:theme="@style/AppTheme"
android:windowSoftInputMode="adjustUnspecified|stateHidden">
</activity>
</application>

<!-- 一个为了Demo能更好保活的前台服务 -->
<service android:name=".service.GeniusService" />

</application>
</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import net.x52im.mobileimsdk.android.conf.ConfigEntity;
import net.x52im.mobileimsdk.android.core.LocalDataSender;
import net.x52im.mobileimsdk.android.core.LocalSocketProvider;
import net.x52im.mobileimsdk.android.demo.R;

import android.app.Activity;
import android.app.AlertDialog;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,16 @@

import net.x52im.mobileimsdk.android.ClientCoreSDK;
import net.x52im.mobileimsdk.android.core.LocalDataSender;
import net.x52im.mobileimsdk.android.demo.R;
import net.x52im.mobileimsdk.android.demo.service.GeniusService;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
Expand Down Expand Up @@ -77,6 +81,10 @@ protected void onCreate(Bundle savedInstanceState)
initViews();
initListeners();
initOthers();

// 启动前台服务(注意:该服务仅用于提升Demo的运行优先级,确保在高版本
// Andriod系统上进程保活和网络保活,此服务与SDK本身无关,也不是必须的)
doBindService();
}

/**
Expand All @@ -87,19 +95,23 @@ public void onBackPressed()
{
super.onBackPressed();

// ** 注意:Android程序要么就别处理,要处理就一定
// 要退干净,否则会有意想不到的问题哦!
// ** 注意:Android程序要么就别处理,要处理就一定要退干净,否则会有意想不到的问题哦!
// 退出登陆
doLogout();
// 退出程序
doExit();
}


@Override
protected void onDestroy()
{
// 释放IM占用资源
IMClientManager.getInstance(this).release();
//

// 解绑前台服务(注意:该服务仅用于提升Demo的运行优先级,确保在高版本
// Andriod系统上进程保活和网络保活,此服务与SDK本身无关,也不是必须的)
doUnbindService();

super.onDestroy();
}

Expand Down Expand Up @@ -357,4 +369,44 @@ public enum ChatInfoColorType
green,
}
//--------------------------------------------------------------- inner classes END

//--------------------------------------------------------------- 前台服务相关代码 START
/** 前台服务对象(绑定MobileIMSDK的Demo后,确保Demo能常驻内存,因为Andriod高版本对于进程保活、网络保活现在限制非常严格) */
private GeniusService boundService;

/** 绑定时需要使用的连接对象 */
private ServiceConnection serviceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
boundService = ((GeniusService.LocalBinder)service).getService();
}

public void onServiceDisconnected(ComponentName className)
{
boundService = null;
}
};

/**
* 将本activity与后台服务绑定起来.
*/
protected void doBindService()
{
this.getApplicationContext().bindService(new Intent(this.getApplicationContext(), GeniusService.class), serviceConnection, Context.BIND_AUTO_CREATE);
}

/**
* 解绑服务(服务将失去功能,随时会被系统回收).
*/
protected void doUnbindService()
{
try{
this.getApplicationContext().unbindService(serviceConnection);
}
catch (Exception e){
// Log.w(TAG, e);
}
}
//--------------------------------------------------------------- 前台服务相关代码 END
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;

import net.x52im.mobileimsdk.android.demo.R;

/**
* 应用程序启动类:显示闪屏界面并跳转到主界面.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package net.x52im.mobileimsdk.android.demo.service;

import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import net.x52im.mobileimsdk.android.demo.R;
import net.x52im.mobileimsdk.android.demo.SplashScreenActivity;

import androidx.core.app.NotificationCompat;

/**
* 一个用于演示的前台服务实现类(本类代码,来自于RainbowChat产品:http://www.52im.net/thread-19-1-1.html)。
* <p>
* 目前的唯一作用是:作为前台服务,提升Demo的运行优先级,确保在高版本Andriod系统上进程保活和网络保活.
*
* 注意:该服务与MobileIMSDK本身无关,也不是必须的!
*
* @author Jack Jiang(http://www.52im.net/space-uid-1.html)
* @version 1.0
*/
public class GeniusService extends Service
{
final static String TAG = GeniusService.class.getSimpleName();

private NotificationManager mNM;

/**
* Class for clients to access. Because we know this service always runs in
* the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder
{
public GeniusService getService()
{
return GeniusService.this;
}
}

@Override
public void onCreate()
{
mNM = getNotificationManager(this);

// Display a notification about us starting. We put an icon in the status bar.
showNotification();
}

@Override
public void onDestroy()
{
//将service从前台移除,并允许随时被系统回收
this.stopForeground(true);
// Tell the user we stopped.
Log.d(TAG, "服务Destroy了哦!");
}

@Override
public IBinder onBind(Intent intent)
{
return mBinder;
}

// This is the object that receives interactions from clients. See RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();

/**
* Show a notification while this service is running.
*/
private void showNotification()
{
Application app = (Application)this.getApplicationContext();

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClass(this, SplashScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);

String appName = this.getResources().getString(R.string.app_name);

// 创建一个Notification
Notification notification = createNotification(app , contentIntent, appName+" 正在运行中 ..."
, "点击回到 "+appName+" 的Demo", R.drawable.icon);

// 让service在前台执行
this.startForeground(999, notification);
}

public static NotificationManager getNotificationManager(Context context)
{
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

// 以下代码,解决在Android 8及以上代码中,无法正常显示Notification或报"Bad notification for startForeground"等问题
NotificationChannel notificationChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
notificationChannel = new NotificationChannel("default_1", "Default Channel", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);

notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

manager.createNotificationChannel(notificationChannel);
}

return manager;
}

/**
* 兼容地方法创建Notification方法。
*
* @param context
* @param pendingIntent
* @param title
* @param text
* @param iconId
* @return
*/
public static Notification createNotification(Context context, PendingIntent pendingIntent, String title, String text, int iconId)
{
// 创建一个Notification Builder,使用NotificationCompat可以更好的兼容Android各系统版本,
// 有关Android Notitication的兼容性、详细设置等,参见:https://www.cnblogs.com/travellife/p/Android-Notification-xiang-jie.html
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "default_1")
.setContentTitle(title)
.setContentText(text)
.setContentIntent(pendingIntent)
// 设置显示在手机最上边的状态栏的图标
.setSmallIcon(iconId);

// 通知的显示等级(Android5.0开始,通知可以显示在锁屏上):
// - VISIBILITY_PRIVATE : 显示基本信息,如通知的图标,但隐藏通知的全部内容
// - VISIBILITY_PUBLIC : 显示通知的全部内容
// - VISIBILITY_SECRET : 不显示任何内容,包括图标
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

// 创建一个Notification
Notification notification = builder.build();

return notification;
}
}
Binary file not shown.
2 changes: 1 addition & 1 deletion demo_src/UDP_Client/MobileIMSDK4aDemo_udp/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ android {
minSdkVersion 14
targetSdkVersion 29
versionCode 105
versionName "v5.0b200917.1"
versionName "v5.0b201015.1"
//testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- Android 9.0中需要此权限的添加,不然崩溃 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<application
android:allowBackup="true"
Expand Down Expand Up @@ -39,6 +41,9 @@
android:windowSoftInputMode="adjustUnspecified|stateHidden"
tools:ignore="LockedOrientationActivity">
</activity>
</application>

<!-- 一个为了Demo能更好保活的前台服务 -->
<service android:name=".service.GeniusService" />

</application>
</manifest>
Loading

0 comments on commit 709d7fa

Please sign in to comment.