DEV Community

HarmonyOS
HarmonyOS

Posted on

[Smart Watch] [API 6] Smart Watch Background Keepalive Solution_Java

Read the original article:[Smart Watch] [API 6] Smart Watch Background Keepalive Solution_Java

Background Keepalive Solution

1.1 Keepalive Solution

Keepalive solution: startLocating + foreground service setting

1.2 Configuring Permissions

Permission for configuring the config.json file

"reqPermissions": [
      {
        "name": "ohos.permission.KEEP_BACKGROUND_RUNNING"
      },
      {
        "reason":" $string:XXXX"
        "name": "ohos.permission.LOCATION"
      },
      {
        " reason ":" $string:XXXX"
        "name": "ohos.permission.LOCATION_IN_BACKGROUND"
      }
]
Enter fullscreen mode Exit fullscreen mode

1.3 Configuring Service Types

BackgroundModes is configured in the config.json file

{
        "name": "com.harmonyos.wearable.LocationServiceAbility",
        "description": "$string:locationserviceability_description",
        "type": "service",
        "backgroundModes": [
          "location",
          "bluetoothInteraction"
        ],
        "icon": "$media:icon"
}
Enter fullscreen mode Exit fullscreen mode

1.4 Dynamically apply for sensitive permissions in the MainAbility code

private void requestPermission() {
       String[] permissions = {
                     "ohos.permission.LOCATION",
                     "ohos.permission.LOCATION_IN_BACKGROUND"
       };
       for (int index = 0; index < permissions.length; index++) {
              if (verifySelfPermission(permissions[index]) != IBundleManager.PERMISSION_GRANTED) {
                     if (canRequestPermission(permissions[index])) {
                            requestPermissionsFromUser(permissions, 0);
                     }
              }
       }
}Copy codeCopy code
Enter fullscreen mode Exit fullscreen mode

1.5 Modify the following files

MainAbilitySlice.java

LocationServiceAbility.java

ability_main.xml

config.json

1.6 MainAbilitySlice.java

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel TAG = new HiLogLabel(3, 0x00201, "--HarmonyWearable--");
    private MyEventHandler myHandler;
    private String regex = "-->";
    private int number;
    private Intent mIntent;
    private Timer timer;
    private Text rate;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        initListener();
        myHandler = new MyEventHandler(EventRunner.current());
        requestPermission();
    }

    private void initListener() {
        findComponentById(ResourceTable.Id_button_create).setClickedListener(component -> {
            startLocationService();
        });

        findComponentById(ResourceTable.Id_button_cancel).setClickedListener(component -> {
            stopLocationService();
        });

        findComponentById(ResourceTable.Id_button_time).setClickedListener(va -> {
            startTimer();
        });

        rate = (Text) findComponentById(ResourceTable.Id_text_rate);
        findComponentById(ResourceTable.Id_button_time_cancel).setClickedListener(va -> {
            rate.setText("定时");
            stopTimer();
        });
    }

    private void startTimer() {
        stopTimer();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                myHandler.sendEvent(InnerEvent.get());
            }
        }, 0, 1000);
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void requestPermission() {
        String[] permissions = {
                "ohos.permission.LOCATION",
                "ohos.permission.LOCATION_IN_BACKGROUND"
        };
        for (int index = 0; index < permissions.length; index++) {
            if (verifySelfPermission(permissions[index]) != IBundleManager.PERMISSION_GRANTED) {
                if (canRequestPermission(permissions[index])) {
                    requestPermissionsFromUser(permissions, 0);
                }
            }
        }
    }

    public void startLocationService() {
        mIntent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(LocationServiceAbility.class.getName())
                .build();
        mIntent.setOperation(operation);
        startAbility(mIntent);
    }

    private void stopLocationService() {
        stopAbility(mIntent);
    }

    class MyEventHandler extends EventHandler {
        MyEventHandler(EventRunner runner) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            number++;
            rate.setText( getNowTime()+ regex +number);
            HiLog.info(TAG, "::processEvent::"+getNowTime()+ regex +number);
        }
    }

    private String getNowTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sd = new SimpleDateFormat("HH:mm:ss");
        String format = sd.format(date);
        return format;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
Enter fullscreen mode Exit fullscreen mode

1.7 LocationServiceAbility.java

public class LocationServiceAbility extends Ability {
    private static final HiLogLabel TAG = new HiLogLabel(3, 0x00201, "--HarmonyWearable--");

    private static final int NOTIFICATION_ID = 1001;
    private Locator mlocator;
    private MyLocatorCallback mlocatorCallback;
    private  NotificationRequest request;
    private Context mContext;

    @Override
    public void onStart(Intent intent) {
        HiLog.debug(TAG, "LocationServiceAbility::onStart");
        super.onStart(intent);
        mContext = this;
        startKeepBackground();
    }

    private void startKeepBackground() {
        if(request != null && mlocator != null) {
            HiLog.info(TAG, "::!= null");
            return;
        }
        HiLog.info(TAG, "::startKeepBackground ");
        // 创建通知
        request = new NotificationRequest(NOTIFICATION_ID);
        NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent()
                .setTitle("BKeepAlive").setText("doing workout");
        NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
        request.setContent(notificationContent);

        keepBackgroundRunning(NOTIFICATION_ID, request);

        mlocator = new Locator(mContext);
        mlocatorCallback = new MyLocatorCallback();
        RequestParam  mrequestParam = new RequestParam(RequestParam.PRIORITY_FAST_FIRST_FIX,60,0);
        mlocator.startLocating(mrequestParam, mlocatorCallback);
    }

    public class MyLocatorCallback implements LocatorCallback {
        @Override
        public void onLocationReport(Location location) {
            HiLog.debug(TAG,"::result:"+ location.getLatitude()+"::"+location.getLongitude());
        }

        @Override
        public void onStatusChanged(int type) {
            HiLog.debug(TAG,"::onStatusChanged:"+type);
        }

        @Override
        public void onErrorReport(int type) {

        }
    }

    @Override
    public void onBackground() {
        super.onBackground();
    }

    @Override
    public void onStop() {
        super.onStop();
        HiLog.debug(TAG, "LocationServiceAbility::onStop");
        cancelLocating();
        cancelNotification();

    }

    @Override
    public void onCommand(Intent intent, boolean restart, int startId) {
        super.onCommand(intent, restart, startId);
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        return super.onConnect(intent);
    }

    @Override
    public void onDisconnect(Intent intent) {
        super.onDisconnect(intent);
    }

    private void cancelNotification() {
        try {
            NotificationHelper.cancelNotification(NOTIFICATION_ID);
        } catch (RemoteException e) {
            HiLog.error(TAG, "::cancelNotification error");
        }
        cancelBackgroundRunning();
        request = null;
    }

    private void cancelLocating () {
        if(mlocator != null) {
            mlocator.stopLocating(mlocatorCallback);
            mlocatorCallback = null;
            mlocator = null;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

1.8 ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:orientation="vertical">

    <Button
        ohos:id="$+id:button_create"
        ohos:width="match_parent"
        ohos:top_margin="10vp"
        ohos:height="30vp"
        ohos:layout_alignment="horizontal_center"
        ohos:background_element="$graphic:selector_button"
        ohos:text="打开定位服务"
        ohos:text_size="15fp"
        />

    <Button
        ohos:id="$+id:button_cancel"
        ohos:width="match_parent"
        ohos:top_margin="10vp"
        ohos:height="30vp"
        ohos:layout_alignment="horizontal_center"
        ohos:background_element="cyan"
        ohos:text="取消定位服务"
        ohos:text_size="15fp"
        />
    <Button
        ohos:id="$+id:button_time"
        ohos:width="match_parent"
        ohos:top_margin="10vp"
        ohos:height="30vp"
        ohos:layout_alignment="horizontal_center"
        ohos:background_element="cyan"
        ohos:text="打开定时器"
        ohos:text_size="15fp"
        />

    <Button
        ohos:id="$+id:button_time_cancel"
        ohos:width="match_parent"
        ohos:top_margin="10vp"
        ohos:height="30vp"
        ohos:layout_alignment="horizontal_center"
        ohos:background_element="cyan"
        ohos:text="关闭定时器"
        ohos:text_size="15fp"
        />

    <Text
        ohos:id="$+id:text_rate"
        ohos:height="30vp"
        ohos:width="match_parent"
        ohos:background_element="gray"
        ohos:layout_alignment="horizontal_center"
        ohos:text="定时器"
        ohos:text_color="#FFEEE6E6"
        ohos:text_alignment="horizontal_center"
        ohos:text_size="15fp"
        ohos:top_margin="20vp"
        ohos:top_padding="5vp"
        />
</DirectionalLayout>
Enter fullscreen mode Exit fullscreen mode

1.9 config.json

{
  "app": {
    "bundleName": "com.harmonyos.wearable",
    "vendor": "example",
    "version": {
      "code": 1000000,
      "name": "1.0.0"
    }
  },
  "deviceConfig": {
  },
  "module": {
    "package": "com.harmonyos.wearable",
    "name": ".MyApplication",
    "mainAbility": "com.harmonyos.wearable.MainAbility",
    "deviceType": [
      "wearable"
    ],
    "distro": {
      "deliveryWithInstall": true,
      "moduleName": "entry",
      "moduleType": "entry",
      "installationFree": false
    },
    "abilities": [
      {
        "skills": [
          {
            "entities": [
              "entity.system.home"
            ],
            "actions": [
              "action.system.home"
            ]
          }
        ],
        "name": "com.harmonyos.wearable.MainAbility",
        "description": "$string:mainability_description",
        "icon": "$media:icon",
        "label": "$string:entry_MainAbility",
        "launchType": "standard",
        "orientation": "unspecified",
        "visible": true,
        "type": "page"
      },
      {
        "name": "com.harmonyos.wearable.LocationServiceAbility",
        "description": "$string:locationserviceability_description",
        "type": "service",
        "backgroundModes": [
          "location",
          "bluetoothInteraction"
        ],
        "icon": "$media:icon"
      }
    ],
    "reqPermissions": [
      {
        "name": "ohos.permission.KEEP_BACKGROUND_RUNNING"
      },
      {
        "reason": "",
        "name": "ohos.permission.LOCATION"
      },
      {
        "reason": "",
        "name": "ohos.permission.LOCATION_IN_BACKGROUND"
      }]
  }
}
Enter fullscreen mode Exit fullscreen mode

Written by Aycanur Ucar

Top comments (0)