Enable and disable Keep Alive according to device Doze mode

This commit is contained in:
Erwan Croze 2016-12-08 16:51:06 +01:00
parent 1c7907e217
commit 32011c8f72
9 changed files with 152 additions and 94 deletions

View file

@ -133,7 +133,7 @@ public class CallActivity extends Activity implements OnClickListener, SensorEve
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
instance = this; instance = this;
if (getResources().getBoolean(R.bool.orientation_portrait_only)) { if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} }
@ -166,7 +166,7 @@ public class CallActivity extends Activity implements OnClickListener, SensorEve
public void messageReceived(LinphoneCore lc, LinphoneChatRoom cr, LinphoneChatMessage message) { public void messageReceived(LinphoneCore lc, LinphoneChatRoom cr, LinphoneChatMessage message) {
displayMissedChats(); displayMissedChats();
} }
@Override @Override
public void callState(LinphoneCore lc, final LinphoneCall call, LinphoneCall.State state, String message) { public void callState(LinphoneCore lc, final LinphoneCall call, LinphoneCall.State state, String message) {
if (LinphoneManager.getLc().getCallsNb() == 0) { if (LinphoneManager.getLc().getCallsNb() == 0) {
@ -436,7 +436,7 @@ public class CallActivity extends Activity implements OnClickListener, SensorEve
public void checkAndRequestPermission(String permission, int result) { public void checkAndRequestPermission(String permission, int result) {
int permissionGranted = getPackageManager().checkPermission(permission, getPackageName()); int permissionGranted = getPackageManager().checkPermission(permission, getPackageName());
Log.i("[Permission] " + permission + " is " + (permissionGranted == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); Log.i("[Permission] " + permission + " is " + (permissionGranted == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
if (permissionGranted != PackageManager.PERMISSION_GRANTED) { if (permissionGranted != PackageManager.PERMISSION_GRANTED) {
if (LinphonePreferences.instance().firstTimeAskingForPermission(permission) || ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) { if (LinphonePreferences.instance().firstTimeAskingForPermission(permission) || ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
Log.i("[Permission] Asking for " + permission); Log.i("[Permission] Asking for " + permission);
@ -450,7 +450,7 @@ public class CallActivity extends Activity implements OnClickListener, SensorEve
for (int i = 0; i < permissions.length; i++) { for (int i = 0; i < permissions.length; i++) {
Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); Log.i("[Permission] " + permissions[i] + " is " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
} }
switch (requestCode) { switch (requestCode) {
case PERMISSIONS_REQUEST_CAMERA: case PERMISSIONS_REQUEST_CAMERA:
UIThreadDispatcher.dispatch(new Runnable() { UIThreadDispatcher.dispatch(new Runnable() {
@ -618,7 +618,7 @@ public class CallActivity extends Activity implements OnClickListener, SensorEve
if (id == R.id.video) { if (id == R.id.video) {
int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()); int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
if (camera == PackageManager.PERMISSION_GRANTED) { if (camera == PackageManager.PERMISSION_GRANTED) {
disableVideo(isVideoEnabled(LinphoneManager.getLc().getCurrentCall())); disableVideo(isVideoEnabled(LinphoneManager.getLc().getCurrentCall()));
} else { } else {
@ -629,7 +629,7 @@ public class CallActivity extends Activity implements OnClickListener, SensorEve
else if (id == R.id.micro) { else if (id == R.id.micro) {
int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()); int recordAudio = getPackageManager().checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName());
Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); Log.i("[Permission] Record audio permission is " + (recordAudio == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
if (recordAudio == PackageManager.PERMISSION_GRANTED) { if (recordAudio == PackageManager.PERMISSION_GRANTED) {
toggleMicro(); toggleMicro();
} else { } else {
@ -783,7 +783,7 @@ public class CallActivity extends Activity implements OnClickListener, SensorEve
//Check if the call is not terminated //Check if the call is not terminated
if(call.getState() == State.CallEnd || call.getState() == State.CallReleased) return; if(call.getState() == State.CallEnd || call.getState() == State.CallReleased) return;
if (!displayVideo) { if (!displayVideo) {
showAudioView(); showAudioView();
} else { } else {
@ -1143,7 +1143,7 @@ public class CallActivity extends Activity implements OnClickListener, SensorEve
public void onClick(View view) { public void onClick(View view) {
int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName()); int camera = getPackageManager().checkPermission(Manifest.permission.CAMERA, getPackageName());
Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied")); Log.i("[Permission] Camera permission is " + (camera == PackageManager.PERMISSION_GRANTED ? "granted" : "denied"));
if (camera == PackageManager.PERMISSION_GRANTED) { if (camera == PackageManager.PERMISSION_GRANTED) {
CallActivity.instance().acceptCallUpdate(true); CallActivity.instance().acceptCallUpdate(true);
} else { } else {
@ -1568,14 +1568,14 @@ public class CallActivity extends Activity implements OnClickListener, SensorEve
public void onAccuracyChanged(Sensor sensor, int accuracy) { public void onAccuracyChanged(Sensor sensor, int accuracy) {
} }
private void displayMissedChats() { private void displayMissedChats() {
int count = 0; int count = 0;
LinphoneChatRoom[] chats = LinphoneManager.getLc().getChatRooms(); LinphoneChatRoom[] chats = LinphoneManager.getLc().getChatRooms();
for (LinphoneChatRoom chatroom : chats) { for (LinphoneChatRoom chatroom : chats) {
count += chatroom.getUnreadMessagesCount(); count += chatroom.getUnreadMessagesCount();
} }
if (count > 0) { if (count > 0) {
missedChats.setText(count + ""); missedChats.setText(count + "");
missedChats.setVisibility(View.VISIBLE); missedChats.setVisibility(View.VISIBLE);

View file

@ -0,0 +1,35 @@
package org.linphone;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.PowerManager;
import org.linphone.core.LinphoneCore;
import org.linphone.core.LinphoneCoreFactory;
import org.linphone.mediastream.Log;
/*
* Purpose of this receiver is to disable keep alives when device is on idle
* */
public class DozeReceiver extends android.content.BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
PowerManager pm;
if (!LinphoneService.isReady()) return;
boolean isDebugEnabled = LinphonePreferences.instance().isDebugEnabled();
LinphoneCoreFactory.instance().enableLogCollection(isDebugEnabled);
LinphoneCoreFactory.instance().setDebugMode(isDebugEnabled, context.getString(R.string.app_name));
LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
if (lc == null) return;
pm = (PowerManager) context.getSystemService(context.POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
boolean dozeM = pm.isDeviceIdleMode();
Log.i("[DozeReceiver] Idle Mode: " + dozeM);
LinphoneManager.getInstance().setDozeModeEnabled(dozeM);
LinphoneManager.getInstance().updateNetworkReachability();
}
}
}

View file

@ -44,7 +44,7 @@ public class KeepAliveReceiver extends BroadcastReceiver {
LinphoneCoreFactory.instance().setDebugMode(isDebugEnabled, context.getString(R.string.app_name)); LinphoneCoreFactory.instance().setDebugMode(isDebugEnabled, context.getString(R.string.app_name));
LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
if (lc == null) return; if (lc == null) return;
String action = intent.getAction(); String action = intent.getAction();
if (action == null) { if (action == null) {
Log.i("[KeepAlive] Refresh registers"); Log.i("[KeepAlive] Refresh registers");

View file

@ -31,9 +31,9 @@ import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
/** /**
* *
* Launch Linphone main activity when Service is ready. * Launch Linphone main activity when Service is ready.
* *
* @author Guillaume Beraudo * @author Guillaume Beraudo
* *
*/ */
@ -45,19 +45,19 @@ public class LinphoneLauncherActivity extends Activity {
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
// Hack to avoid to draw twice LinphoneActivity on tablets // Hack to avoid to draw twice LinphoneActivity on tablets
if (getResources().getBoolean(R.bool.orientation_portrait_only)) { if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} }
setContentView(R.layout.launch_screen); setContentView(R.layout.launch_screen);
mHandler = new Handler(); mHandler = new Handler();
if (LinphoneService.isReady()) { if (LinphoneService.isReady()) {
onServiceReady(); onServiceReady();
} else { } else {
// start linphone as background // start linphone as background
startService(new Intent(ACTION_MAIN).setClass(this, LinphoneService.class)); startService(new Intent(ACTION_MAIN).setClass(this, LinphoneService.class));
mThread = new ServiceWaitThread(); mThread = new ServiceWaitThread();
mThread.start(); mThread.start();
@ -78,7 +78,7 @@ public class LinphoneLauncherActivity extends Activity {
if (Version.sdkAboveOrEqual(Version.API11_HONEYCOMB_30)) { if (Version.sdkAboveOrEqual(Version.API11_HONEYCOMB_30)) {
BluetoothManager.getInstance().initBluetooth(); BluetoothManager.getInstance().initBluetooth();
} }
mHandler.postDelayed(new Runnable() { mHandler.postDelayed(new Runnable() {
@Override @Override
public void run() { public void run() {

View file

@ -140,10 +140,13 @@ public class LinphoneManager implements LinphoneCoreListener, LinphoneChatMessag
private static boolean sExited; private static boolean sExited;
private boolean mAudioFocused; private boolean mAudioFocused;
private boolean echoTesterIsRunning; private boolean echoTesterIsRunning;
private boolean dozeModeEnabled;
private int mLastNetworkType=-1; private int mLastNetworkType=-1;
private ConnectivityManager mConnectivityManager; private ConnectivityManager mConnectivityManager;
private BroadcastReceiver mKeepAliveReceiver; private BroadcastReceiver mKeepAliveReceiver;
private BroadcastReceiver mDozeReceiver;
private IntentFilter mKeepAliveIntentFilter; private IntentFilter mKeepAliveIntentFilter;
private IntentFilter mDozeIntentFilter;
private Handler mHandler = new Handler(); private Handler mHandler = new Handler();
private WakeLock mIncallWakeLock; private WakeLock mIncallWakeLock;
private LinphoneAccountCreator accountCreator; private LinphoneAccountCreator accountCreator;
@ -188,6 +191,12 @@ public class LinphoneManager implements LinphoneCoreListener, LinphoneChatMessag
mConnectivityManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); mConnectivityManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
mR = c.getResources(); mR = c.getResources();
mPendingChatFileMessage = new ArrayList<LinphoneChatMessage>(); mPendingChatFileMessage = new ArrayList<LinphoneChatMessage>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
dozeModeEnabled = ((PowerManager)c.getSystemService(c.POWER_SERVICE)).isDeviceIdleMode();
} else {
dozeModeEnabled = false;
}
} }
private static final int LINPHONE_VOLUME_STREAM = STREAM_VOICE_CALL; private static final int LINPHONE_VOLUME_STREAM = STREAM_VOICE_CALL;
@ -663,6 +672,7 @@ public class LinphoneManager implements LinphoneCoreListener, LinphoneChatMessag
finally { finally {
try { try {
mServiceContext.unregisterReceiver(mKeepAliveReceiver); mServiceContext.unregisterReceiver(mKeepAliveReceiver);
mServiceContext.unregisterReceiver(mDozeReceiver);
} catch (Exception e) { } catch (Exception e) {
Log.e(e); Log.e(e);
} }
@ -679,6 +689,7 @@ public class LinphoneManager implements LinphoneCoreListener, LinphoneChatMessag
be sent by the system. be sent by the system.
*/ */
mServiceContext.registerReceiver(mKeepAliveReceiver, mKeepAliveIntentFilter); mServiceContext.registerReceiver(mKeepAliveReceiver, mKeepAliveIntentFilter);
mServiceContext.registerReceiver(mDozeReceiver, mDozeIntentFilter);
sExited = false; sExited = false;
} }
@ -798,9 +809,17 @@ public class LinphoneManager implements LinphoneCoreListener, LinphoneChatMessag
*/ */
mKeepAliveIntentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON); mKeepAliveIntentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
mKeepAliveIntentFilter.addAction(Intent.ACTION_SCREEN_OFF); mKeepAliveIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
mKeepAliveReceiver = new KeepAliveReceiver(); mKeepAliveReceiver = new KeepAliveReceiver();
mServiceContext.registerReceiver(mKeepAliveReceiver, mKeepAliveIntentFilter); mServiceContext.registerReceiver(mKeepAliveReceiver, mKeepAliveIntentFilter);
mDozeIntentFilter = new IntentFilter(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
mDozeIntentFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
mDozeReceiver = new DozeReceiver();
mServiceContext.registerReceiver(mDozeReceiver, mDozeIntentFilter);
updateNetworkReachability(); updateNetworkReachability();
resetCameraFromPreferences(); resetCameraFromPreferences();
@ -870,7 +889,7 @@ public class LinphoneManager implements LinphoneCoreListener, LinphoneChatMessag
ConnectivityManager cm = (ConnectivityManager) mServiceContext.getSystemService(Context.CONNECTIVITY_SERVICE); ConnectivityManager cm = (ConnectivityManager) mServiceContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo eventInfo = cm.getActiveNetworkInfo(); NetworkInfo eventInfo = cm.getActiveNetworkInfo();
if (eventInfo == null || eventInfo.getState() == NetworkInfo.State.DISCONNECTED) { if (eventInfo == null || eventInfo.getState() == NetworkInfo.State.DISCONNECTED || dozeModeEnabled) {
Log.i("No connectivity: setting network unreachable"); Log.i("No connectivity: setting network unreachable");
mLc.setNetworkReachable(false); mLc.setNetworkReachable(false);
} else if (eventInfo.getState() == NetworkInfo.State.CONNECTED){ } else if (eventInfo.getState() == NetworkInfo.State.CONNECTED){
@ -1495,6 +1514,10 @@ public class LinphoneManager implements LinphoneCoreListener, LinphoneChatMessag
dialog.show(); dialog.show();
} }
public void setDozeModeEnabled(boolean b) {
dozeModeEnabled = b;
}
@SuppressWarnings("serial") @SuppressWarnings("serial")
public static class LinphoneConfigException extends LinphoneException { public static class LinphoneConfigException extends LinphoneException {

View file

@ -64,16 +64,16 @@ import android.provider.MediaStore;
import android.view.WindowManager; import android.view.WindowManager;
/** /**
* *
* Linphone service, reacting to Incoming calls, ...<br /> * Linphone service, reacting to Incoming calls, ...<br />
* *
* Roles include:<ul> * Roles include:<ul>
* <li>Initializing LinphoneManager</li> * <li>Initializing LinphoneManager</li>
* <li>Starting C libLinphone through LinphoneManager</li> * <li>Starting C libLinphone through LinphoneManager</li>
* <li>Reacting to LinphoneManager state changes</li> * <li>Reacting to LinphoneManager state changes</li>
* <li>Delegating GUI state change actions to GUI listener</li> * <li>Delegating GUI state change actions to GUI listener</li>
* *
* *
* @author Guillaume Beraudo * @author Guillaume Beraudo
* *
*/ */
@ -86,15 +86,15 @@ public final class LinphoneService extends Service {
/*private static final int IC_LEVEL_GREEN=1; /*private static final int IC_LEVEL_GREEN=1;
private static final int IC_LEVEL_RED=2;*/ private static final int IC_LEVEL_RED=2;*/
//public static final int IC_LEVEL_OFFLINE=3; //public static final int IC_LEVEL_OFFLINE=3;
private static LinphoneService instance; private static LinphoneService instance;
private final static int NOTIF_ID=1; private final static int NOTIF_ID=1;
private final static int INCALL_NOTIF_ID=2; private final static int INCALL_NOTIF_ID=2;
private final static int MESSAGE_NOTIF_ID=3; private final static int MESSAGE_NOTIF_ID=3;
private final static int CUSTOM_NOTIF_ID=4; private final static int CUSTOM_NOTIF_ID=4;
private final static int MISSED_NOTIF_ID=5; private final static int MISSED_NOTIF_ID=5;
public static boolean isReady() { public static boolean isReady() {
return instance != null && instance.mTestDelayElapsed; return instance != null && instance.mTestDelayElapsed;
} }
@ -255,18 +255,18 @@ public final class LinphoneService extends Service {
public int getMessageNotifCount() { public int getMessageNotifCount() {
return mMsgNotifCount; return mMsgNotifCount;
} }
public void resetMessageNotifCount() { public void resetMessageNotifCount() {
mMsgNotifCount = 0; mMsgNotifCount = 0;
} }
private boolean displayServiceNotification() { private boolean displayServiceNotification() {
return LinphonePreferences.instance().getServiceNotificationVisibility(); return LinphonePreferences.instance().getServiceNotificationVisibility();
} }
public void showServiceNotification() { public void showServiceNotification() {
startForegroundCompat(NOTIF_ID, mNotif); startForegroundCompat(NOTIF_ID, mNotif);
LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
if (lc == null) return; if (lc == null) return;
LinphoneProxyConfig lpc = lc.getDefaultProxyConfig(); LinphoneProxyConfig lpc = lc.getDefaultProxyConfig();
@ -280,7 +280,7 @@ public final class LinphoneService extends Service {
sendNotification(IC_LEVEL_ORANGE, R.string.notification_started); sendNotification(IC_LEVEL_ORANGE, R.string.notification_started);
} }
} }
public void hideServiceNotification() { public void hideServiceNotification() {
stopForegroundCompat(NOTIF_ID); stopForegroundCompat(NOTIF_ID);
} }
@ -300,7 +300,7 @@ public final class LinphoneService extends Service {
boolean isDebugEnabled = LinphonePreferences.instance().isDebugEnabled(); boolean isDebugEnabled = LinphonePreferences.instance().isDebugEnabled();
LinphoneCoreFactory.instance().enableLogCollection(isDebugEnabled); LinphoneCoreFactory.instance().enableLogCollection(isDebugEnabled);
LinphoneCoreFactory.instance().setDebugMode(isDebugEnabled, getString(R.string.app_name)); LinphoneCoreFactory.instance().setDebugMode(isDebugEnabled, getString(R.string.app_name));
// Dump some debugging information to the logs // Dump some debugging information to the logs
Log.i(START_LINPHONE_LOGS); Log.i(START_LINPHONE_LOGS);
dumpDeviceInformation(); dumpDeviceInformation();
@ -312,7 +312,7 @@ public final class LinphoneService extends Service {
Intent notifIntent = new Intent(this, incomingReceivedActivity); Intent notifIntent = new Intent(this, incomingReceivedActivity);
notifIntent.putExtra("Notification", true); notifIntent.putExtra("Notification", true);
mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent missedCallNotifIntent = new Intent(this, incomingReceivedActivity); Intent missedCallNotifIntent = new Intent(this, incomingReceivedActivity);
missedCallNotifIntent.putExtra("GoToHistory", true); missedCallNotifIntent.putExtra("GoToHistory", true);
mMissedCallsNotifContentIntent = PendingIntent.getActivity(this, 0, missedCallNotifIntent, PendingIntent.FLAG_UPDATE_CURRENT); mMissedCallsNotifContentIntent = PendingIntent.getActivity(this, 0, missedCallNotifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
@ -333,7 +333,7 @@ public final class LinphoneService extends Service {
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
Log.e(e); Log.e(e);
} }
LinphoneManager.getLc().addListener(mListener = new LinphoneCoreListenerBase() { LinphoneManager.getLc().addListener(mListener = new LinphoneCoreListenerBase() {
@Override @Override
public void callState(LinphoneCore lc, LinphoneCall call, LinphoneCall.State state, String message) { public void callState(LinphoneCore lc, LinphoneCall call, LinphoneCall.State state, String message) {
@ -341,15 +341,15 @@ public final class LinphoneService extends Service {
Log.i("Service not ready, discarding call state change to ",state.toString()); Log.i("Service not ready, discarding call state change to ",state.toString());
return; return;
} }
if (state == LinphoneCall.State.IncomingReceived) { if (state == LinphoneCall.State.IncomingReceived) {
onIncomingReceived(); onIncomingReceived();
} }
if (state == State.CallEnd || state == State.CallReleased || state == State.Error) { if (state == State.CallEnd || state == State.CallReleased || state == State.Error) {
destroyOverlay(); destroyOverlay();
} }
if (state == State.CallEnd && call.getCallLog().getStatus() == CallStatus.Missed) { if (state == State.CallEnd && call.getCallLog().getStatus() == CallStatus.Missed) {
int missedCallCount = LinphoneManager.getLcIfManagerNotDestroyedOrNull().getMissedCallsCount(); int missedCallCount = LinphoneManager.getLcIfManagerNotDestroyedOrNull().getMissedCallsCount();
String body; String body;
@ -380,7 +380,7 @@ public final class LinphoneService extends Service {
refreshIncallIcon(LinphoneManager.getLc().getCurrentCall()); refreshIncallIcon(LinphoneManager.getLc().getCurrentCall());
} }
} }
@Override @Override
public void globalState(LinphoneCore lc,LinphoneCore.GlobalState state, String message) { public void globalState(LinphoneCore lc,LinphoneCore.GlobalState state, String message) {
if (state == GlobalState.GlobalOn && displayServiceNotification()) { if (state == GlobalState.GlobalOn && displayServiceNotification()) {
@ -398,18 +398,18 @@ public final class LinphoneService extends Service {
if (displayServiceNotification() && state == RegistrationState.RegistrationOk && LinphoneManager.getLc().getDefaultProxyConfig() != null && LinphoneManager.getLc().getDefaultProxyConfig().isRegistered()) { if (displayServiceNotification() && state == RegistrationState.RegistrationOk && LinphoneManager.getLc().getDefaultProxyConfig() != null && LinphoneManager.getLc().getDefaultProxyConfig().isRegistered()) {
sendNotification(IC_LEVEL_ORANGE, R.string.notification_registered); sendNotification(IC_LEVEL_ORANGE, R.string.notification_registered);
} }
if (displayServiceNotification() && (state == RegistrationState.RegistrationFailed || state == RegistrationState.RegistrationCleared) && (LinphoneManager.getLc().getDefaultProxyConfig() == null || !LinphoneManager.getLc().getDefaultProxyConfig().isRegistered())) { if (displayServiceNotification() && (state == RegistrationState.RegistrationFailed || state == RegistrationState.RegistrationCleared) && (LinphoneManager.getLc().getDefaultProxyConfig() == null || !LinphoneManager.getLc().getDefaultProxyConfig().isRegistered())) {
sendNotification(IC_LEVEL_ORANGE, R.string.notification_register_failure); sendNotification(IC_LEVEL_ORANGE, R.string.notification_register_failure);
} }
if (displayServiceNotification() && state == RegistrationState.RegistrationNone) { if (displayServiceNotification() && state == RegistrationState.RegistrationNone) {
sendNotification(IC_LEVEL_ORANGE, R.string.notification_started); sendNotification(IC_LEVEL_ORANGE, R.string.notification_started);
} }
} }
} }
}); });
// Retrieve methods to publish notification and keep Android // Retrieve methods to publish notification and keep Android
// from killing us and keep the audio quality high. // from killing us and keep the audio quality high.
if (Version.sdkStrictlyBelow(Version.API05_ECLAIR_20)) { if (Version.sdkStrictlyBelow(Version.API05_ECLAIR_20)) {
@ -441,29 +441,29 @@ public final class LinphoneService extends Service {
} }
}, 5000); }, 5000);
} }
//make sure the application will at least wakes up every 10 mn //make sure the application will at least wakes up every 10 mn
Intent intent = new Intent(this, KeepAliveReceiver.class); Intent intent = new Intent(this, KeepAliveReceiver.class);
PendingIntent keepAlivePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); PendingIntent keepAlivePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = ((AlarmManager) this.getSystemService(Context.ALARM_SERVICE)); AlarmManager alarmManager = ((AlarmManager) this.getSystemService(Context.ALARM_SERVICE));
Compatibility.scheduleAlarm(alarmManager, AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 600000, keepAlivePendingIntent); Compatibility.scheduleAlarm(alarmManager, AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 600000, keepAlivePendingIntent);
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE); mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
} }
public void createOverlay() { public void createOverlay() {
if (mOverlay != null) destroyOverlay(); if (mOverlay != null) destroyOverlay();
LinphoneCall call = LinphoneManager.getLc().getCurrentCall(); LinphoneCall call = LinphoneManager.getLc().getCurrentCall();
if (call == null || !call.getCurrentParamsCopy().getVideoEnabled()) return; if (call == null || !call.getCurrentParamsCopy().getVideoEnabled()) return;
mOverlay = new LinphoneOverlay(this); mOverlay = new LinphoneOverlay(this);
WindowManager.LayoutParams params = mOverlay.getWindowManagerLayoutParams(); WindowManager.LayoutParams params = mOverlay.getWindowManagerLayoutParams();
params.x = 0; params.x = 0;
params.y = 0; params.y = 0;
mWindowManager.addView(mOverlay, params); mWindowManager.addView(mOverlay, params);
} }
public void destroyOverlay() { public void destroyOverlay() {
if (mOverlay != null) { if (mOverlay != null) {
mWindowManager.removeViewImmediate(mOverlay); mWindowManager.removeViewImmediate(mOverlay);
@ -480,7 +480,7 @@ public final class LinphoneService extends Service {
int notificationTextId = 0; int notificationTextId = 0;
int inconId = 0; int inconId = 0;
switch (state) { switch (state) {
case IDLE: case IDLE:
mNM.cancel(INCALL_NOTIF_ID); mNM.cancel(INCALL_NOTIF_ID);
@ -496,15 +496,15 @@ public final class LinphoneService extends Service {
case VIDEO: case VIDEO:
inconId = R.drawable.topbar_videocall_notification; inconId = R.drawable.topbar_videocall_notification;
notificationTextId = R.string.incall_notif_video; notificationTextId = R.string.incall_notif_video;
break; break;
default: default:
throw new IllegalArgumentException("Unknown state " + state); throw new IllegalArgumentException("Unknown state " + state);
} }
if (LinphoneManager.getLc().getCallsNb() == 0) { if (LinphoneManager.getLc().getCallsNb() == 0) {
return; return;
} }
LinphoneCall call = LinphoneManager.getLc().getCalls()[0]; LinphoneCall call = LinphoneManager.getLc().getCalls()[0];
String userName = call.getRemoteAddress().getUserName(); String userName = call.getRemoteAddress().getUserName();
String domain = call.getRemoteAddress().getDomain(); String domain = call.getRemoteAddress().getDomain();
@ -544,50 +544,50 @@ public final class LinphoneService extends Service {
} }
} }
@Deprecated @Deprecated
public void addNotification(Intent onClickIntent, int iconResourceID, String title, String message) { public void addNotification(Intent onClickIntent, int iconResourceID, String title, String message) {
addCustomNotification(onClickIntent, iconResourceID, title, message, true); addCustomNotification(onClickIntent, iconResourceID, title, message, true);
} }
public void addCustomNotification(Intent onClickIntent, int iconResourceID, String title, String message, boolean isOngoingEvent) { public void addCustomNotification(Intent onClickIntent, int iconResourceID, String title, String message, boolean isOngoingEvent) {
PendingIntent notifContentIntent = PendingIntent.getActivity(this, 0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent notifContentIntent = PendingIntent.getActivity(this, 0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Bitmap bm = null; Bitmap bm = null;
try { try {
bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
} catch (Exception e) { } catch (Exception e) {
} }
mCustomNotif = Compatibility.createNotification(this, title, message, iconResourceID, 0, bm, notifContentIntent, isOngoingEvent,notifcationsPriority); mCustomNotif = Compatibility.createNotification(this, title, message, iconResourceID, 0, bm, notifContentIntent, isOngoingEvent,notifcationsPriority);
mCustomNotif.defaults |= Notification.DEFAULT_VIBRATE; mCustomNotif.defaults |= Notification.DEFAULT_VIBRATE;
mCustomNotif.defaults |= Notification.DEFAULT_SOUND; mCustomNotif.defaults |= Notification.DEFAULT_SOUND;
mCustomNotif.defaults |= Notification.DEFAULT_LIGHTS; mCustomNotif.defaults |= Notification.DEFAULT_LIGHTS;
notifyWrapper(CUSTOM_NOTIF_ID, mCustomNotif); notifyWrapper(CUSTOM_NOTIF_ID, mCustomNotif);
} }
public void removeCustomNotification() { public void removeCustomNotification() {
mNM.cancel(CUSTOM_NOTIF_ID); mNM.cancel(CUSTOM_NOTIF_ID);
resetIntentLaunchedOnNotificationClick(); resetIntentLaunchedOnNotificationClick();
} }
public void displayMessageNotification(String fromSipUri, String fromName, String message) { public void displayMessageNotification(String fromSipUri, String fromName, String message) {
Intent notifIntent = new Intent(this, LinphoneActivity.class); Intent notifIntent = new Intent(this, LinphoneActivity.class);
notifIntent.putExtra("GoToChat", true); notifIntent.putExtra("GoToChat", true);
notifIntent.putExtra("ChatContactSipUri", fromSipUri); notifIntent.putExtra("ChatContactSipUri", fromSipUri);
PendingIntent notifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent notifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (fromName == null) { if (fromName == null) {
fromName = fromSipUri; fromName = fromSipUri;
} }
if (mMsgNotif == null) { if (mMsgNotif == null) {
mMsgNotifCount = 1; mMsgNotifCount = 1;
} else { } else {
mMsgNotifCount++; mMsgNotifCount++;
} }
Uri pictureUri = null; Uri pictureUri = null;
try { try {
LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(LinphoneCoreFactory.instance().createLinphoneAddress(fromSipUri)); LinphoneContact contact = ContactsManager.getInstance().findContactFromAddress(LinphoneCoreFactory.instance().createLinphoneAddress(fromSipUri));
@ -596,7 +596,7 @@ public final class LinphoneService extends Service {
} catch (LinphoneCoreException e1) { } catch (LinphoneCoreException e1) {
Log.e("Cannot parse from address ", e1); Log.e("Cannot parse from address ", e1);
} }
Bitmap bm = null; Bitmap bm = null;
if (pictureUri != null) { if (pictureUri != null) {
try { try {
@ -608,7 +608,7 @@ public final class LinphoneService extends Service {
bm = BitmapFactory.decodeResource(getResources(), R.drawable.topbar_avatar); bm = BitmapFactory.decodeResource(getResources(), R.drawable.topbar_avatar);
} }
mMsgNotif = Compatibility.createMessageNotification(getApplicationContext(), mMsgNotifCount, fromName, message, bm, notifContentIntent); mMsgNotif = Compatibility.createMessageNotification(getApplicationContext(), mMsgNotifCount, fromName, message, bm, notifContentIntent);
notifyWrapper(MESSAGE_NOTIF_ID, mMsgNotif); notifyWrapper(MESSAGE_NOTIF_ID, mMsgNotif);
} }
@ -621,7 +621,7 @@ public final class LinphoneService extends Service {
notifyWrapper(NOTIF_ID, mNotif); notifyWrapper(NOTIF_ID, mNotif);
} }
public void removeMessageNotification() { public void removeMessageNotification() {
mNM.cancel(MESSAGE_NOTIF_ID); mNM.cancel(MESSAGE_NOTIF_ID);
resetIntentLaunchedOnNotificationClick(); resetIntentLaunchedOnNotificationClick();
@ -696,7 +696,7 @@ public final class LinphoneService extends Service {
invokeMethod(mSetForeground, mSetForegroundArgs); invokeMethod(mSetForeground, mSetForegroundArgs);
} }
} }
private void dumpDeviceInformation() { private void dumpDeviceInformation() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("DEVICE=").append(Build.DEVICE).append("\n"); sb.append("DEVICE=").append(Build.DEVICE).append("\n");
@ -724,7 +724,7 @@ public final class LinphoneService extends Service {
Log.i("Linphone version is unknown"); Log.i("Linphone version is unknown");
} }
} }
public void disableNotificationsAutomaticRegistrationStatusContent() { public void disableNotificationsAutomaticRegistrationStatusContent() {
mDisableRegistrationStatus = true; mDisableRegistrationStatus = true;
} }
@ -765,13 +765,13 @@ public final class LinphoneService extends Service {
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
return null; return null;
} }
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override @Override
public void onTaskRemoved(Intent rootIntent) { public void onTaskRemoved(Intent rootIntent) {
if (getResources().getBoolean(R.bool.kill_service_with_task_manager)) { if (getResources().getBoolean(R.bool.kill_service_with_task_manager)) {
Log.d("Task removed, stop service"); Log.d("Task removed, stop service");
// If push is enabled, don't unregister account, otherwise do unregister // If push is enabled, don't unregister account, otherwise do unregister
if (LinphonePreferences.instance().isPushNotificationEnabled()) { if (LinphonePreferences.instance().isPushNotificationEnabled()) {
LinphoneManager.getLc().setNetworkReachable(false); LinphoneManager.getLc().setNetworkReachable(false);
@ -794,7 +794,7 @@ public final class LinphoneService extends Service {
if (lc != null) { if (lc != null) {
lc.removeListener(mListener); lc.removeListener(mListener);
} }
instance = null; instance = null;
getContentResolver().unregisterContentObserver(ContactsManager.getInstance()); getContentResolver().unregisterContentObserver(ContactsManager.getInstance());
LinphoneManager.destroy(); LinphoneManager.destroy();
@ -806,7 +806,7 @@ public final class LinphoneService extends Service {
super.onDestroy(); super.onDestroy();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void setActivityToLaunchOnIncomingReceived(String activityName) { public void setActivityToLaunchOnIncomingReceived(String activityName) {
try { try {
@ -818,17 +818,17 @@ public final class LinphoneService extends Service {
} }
resetIntentLaunchedOnNotificationClick(); resetIntentLaunchedOnNotificationClick();
} }
private void resetIntentLaunchedOnNotificationClick() { private void resetIntentLaunchedOnNotificationClick() {
Intent notifIntent = new Intent(this, incomingReceivedActivity); Intent notifIntent = new Intent(this, incomingReceivedActivity);
mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT); mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
/*if (mNotif != null) { /*if (mNotif != null) {
mNotif.contentIntent = mNotifContentIntent; mNotif.contentIntent = mNotifContentIntent;
} }
notifyWrapper(NOTIF_ID, mNotif);*/ notifyWrapper(NOTIF_ID, mNotif);*/
} }
protected void onIncomingReceived() { protected void onIncomingReceived() {
//wakeup linphone //wakeup linphone
startActivity(new Intent() startActivity(new Intent()

View file

@ -39,46 +39,46 @@ public class PreferencesMigrator {
private LinphonePreferences mNewPrefs; private LinphonePreferences mNewPrefs;
private SharedPreferences mOldPrefs; private SharedPreferences mOldPrefs;
private Resources mResources; private Resources mResources;
public PreferencesMigrator(Context context) { public PreferencesMigrator(Context context) {
mNewPrefs = LinphonePreferences.instance(); mNewPrefs = LinphonePreferences.instance();
mResources = context.getResources(); mResources = context.getResources();
mOldPrefs = PreferenceManager.getDefaultSharedPreferences(context); mOldPrefs = PreferenceManager.getDefaultSharedPreferences(context);
} }
public boolean isEchoMigratioNeeded() { public boolean isEchoMigratioNeeded() {
LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
if (lc == null) { if (lc == null) {
return false; return false;
} }
if (mNewPrefs.isEchoConfigurationUpdated()) { if (mNewPrefs.isEchoConfigurationUpdated()) {
return false; return false;
} }
return (!lc.needsEchoCalibration() && mNewPrefs.isEchoCancellationEnabled()); return (!lc.needsEchoCalibration() && mNewPrefs.isEchoCancellationEnabled());
} }
public void doEchoMigration() { public void doEchoMigration() {
LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
if (lc == null) { if (lc == null) {
return; return;
} }
if (!lc.needsEchoCalibration()) { if (!lc.needsEchoCalibration()) {
mNewPrefs.setEchoCancellation(false); mNewPrefs.setEchoCancellation(false);
} }
} }
public boolean isMigrationNeeded() { public boolean isMigrationNeeded() {
int accountNumber = mOldPrefs.getInt(getString(R.string.pref_extra_accounts), -1); int accountNumber = mOldPrefs.getInt(getString(R.string.pref_extra_accounts), -1);
return accountNumber != -1; return accountNumber != -1;
} }
public void doMigration() { public void doMigration() {
mNewPrefs.firstLaunchSuccessful(); // If migration is needed, it is safe to assume Linphone has already been started once. mNewPrefs.firstLaunchSuccessful(); // If migration is needed, it is safe to assume Linphone has already been started once.
mNewPrefs.removePreviousVersionAuthInfoRemoval(); // Remove flag in linphonerc asking core not to store auths infos mNewPrefs.removePreviousVersionAuthInfoRemoval(); // Remove flag in linphonerc asking core not to store auths infos
mNewPrefs.setFrontCamAsDefault(getPrefBoolean(R.string.pref_video_use_front_camera_key, true)); mNewPrefs.setFrontCamAsDefault(getPrefBoolean(R.string.pref_video_use_front_camera_key, true));
mNewPrefs.setWifiOnlyEnabled(getPrefBoolean(R.string.pref_wifi_only_key, false)); mNewPrefs.setWifiOnlyEnabled(getPrefBoolean(R.string.pref_wifi_only_key, false));
mNewPrefs.useRandomPort(getPrefBoolean(R.string.pref_transport_use_random_ports_key, true), false); mNewPrefs.useRandomPort(getPrefBoolean(R.string.pref_transport_use_random_ports_key, true), false);
@ -89,7 +89,7 @@ public class PreferencesMigrator {
mNewPrefs.setAutoStart(getPrefBoolean(R.string.pref_autostart_key, false)); mNewPrefs.setAutoStart(getPrefBoolean(R.string.pref_autostart_key, false));
mNewPrefs.setSharingPictureServerUrl(getPrefString(R.string.pref_image_sharing_server_key, null)); mNewPrefs.setSharingPictureServerUrl(getPrefString(R.string.pref_image_sharing_server_key, null));
mNewPrefs.setRemoteProvisioningUrl(getPrefString(R.string.pref_remote_provisioning_key, null)); mNewPrefs.setRemoteProvisioningUrl(getPrefString(R.string.pref_remote_provisioning_key, null));
doAccountsMigration(); doAccountsMigration();
deleteAllOldPreferences(); deleteAllOldPreferences();
} }
@ -111,12 +111,12 @@ public class PreferencesMigrator {
mNewPrefs.getConfig().sync(); mNewPrefs.getConfig().sync();
} }
} }
private void doAccountsMigration() { private void doAccountsMigration() {
LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull(); LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
lc.clearAuthInfos(); lc.clearAuthInfos();
lc.clearProxyConfigs(); lc.clearProxyConfigs();
for (int i = 0; i < mOldPrefs.getInt(getString(R.string.pref_extra_accounts), 1); i++) { for (int i = 0; i < mOldPrefs.getInt(getString(R.string.pref_extra_accounts), 1); i++) {
doAccountMigration(i, i == getPrefInt(R.string.pref_default_account_key, 0)); doAccountMigration(i, i == getPrefInt(R.string.pref_default_account_key, 0));
} }
@ -124,7 +124,7 @@ public class PreferencesMigrator {
private void doAccountMigration(int index, boolean isDefaultAccount) { private void doAccountMigration(int index, boolean isDefaultAccount) {
String key = index == 0 ? "" : String.valueOf(index); String key = index == 0 ? "" : String.valueOf(index);
String username = getPrefString(getString(R.string.pref_username_key) + key, null); String username = getPrefString(getString(R.string.pref_username_key) + key, null);
String userid = getPrefString(getString(R.string.pref_auth_userid_key) + key, null); String userid = getPrefString(getString(R.string.pref_auth_userid_key) + key, null);
String password = getPrefString(getString(R.string.pref_passwd_key) + key, null); String password = getPrefString(getString(R.string.pref_passwd_key) + key, null);
@ -140,7 +140,7 @@ public class PreferencesMigrator {
.setPassword(password) .setPassword(password)
.setProxy(proxy) .setProxy(proxy)
.setExpires(expire); .setExpires(expire);
if (getPrefBoolean(getString(R.string.pref_enable_outbound_proxy_key) + key, false)) { if (getPrefBoolean(getString(R.string.pref_enable_outbound_proxy_key) + key, false)) {
builder.setOutboundProxyEnabled(true); builder.setOutboundProxyEnabled(true);
} }
@ -152,13 +152,13 @@ public class PreferencesMigrator {
builder.setContactParameters(contactInfos); builder.setContactParameters(contactInfos);
} }
} }
try { try {
builder.saveNewAccount(); builder.saveNewAccount();
} catch (LinphoneCoreException e) { } catch (LinphoneCoreException e) {
Log.e(e); Log.e(e);
} }
if (isDefaultAccount) { if (isDefaultAccount) {
mNewPrefs.setDefaultAccount(index); mNewPrefs.setDefaultAccount(index);
} }
@ -182,9 +182,9 @@ public class PreferencesMigrator {
private void deleteAllOldPreferences() { private void deleteAllOldPreferences() {
Editor editor = mOldPrefs.edit(); Editor editor = mOldPrefs.edit();
editor.clear(); editor.clear();
editor.commit(); editor.apply();
} }
private String getString(int key) { private String getString(int key) {
return mResources.getString(key); return mResources.getString(key);
} }

View file

@ -117,7 +117,7 @@ public class SettingsFragment extends PreferencesListFragment {
private void removePreviousPreferencesFile() { private void removePreviousPreferencesFile() {
SharedPreferences.Editor editor = getPreferenceManager().getSharedPreferences().edit(); SharedPreferences.Editor editor = getPreferenceManager().getSharedPreferences().edit();
editor.clear(); editor.clear();
editor.commit(); editor.apply();
File dir = new File(getActivity().getFilesDir().getAbsolutePath() + "shared_prefs"); File dir = new File(getActivity().getFilesDir().getAbsolutePath() + "shared_prefs");
LinphoneUtils.recursiveFileRemoval(dir); LinphoneUtils.recursiveFileRemoval(dir);

@ -1 +1 @@
Subproject commit d63b53d1ee7fe9c3d44ae9d294063cb1c030e486 Subproject commit 141c0b6c0991fc79e8988961f2283936ca3c14f7