1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/wizardforcel-android-app-sec-guidebook

Клонировать/Скачать
4.4.1.1.md 6.3 КБ
Копировать Редактировать Web IDE Исходные данные Просмотреть построчно История
gitlife-traslator Отправлено 27.11.2024 20:24 c13bfb7

4.4.1.1 Создание/использование частного сервиса

Частный сервис — это сервис, который не может быть запущен другими приложениями, поэтому он является наиболее безопасным сервисом. Когда вы используете частный сервис, предназначенный только для использования в приложении, вам не нужно беспокоиться о том, что он будет случайно отправлен любому другому приложению, если вы явно намереваетесь использовать его таким образом.

Ниже приведён пример кода для использования сервисов типа startService.

Основные моменты (создание сервиса):

  1. Явно установите для свойства экспорта значение false.
  2. Тщательно и безопасно обрабатывайте полученные намерения, даже если они исходят от того же приложения.
  3. Поскольку запрос исходит из того же приложения, можно отправлять конфиденциальную информацию.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.jssec.android.service.privateservice" >
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:allowBackup="false" >
        <activity
            android:name=".PrivateUserActivity"
            android:label="@string/app_name"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- Private Service derived from Service class -->
        <!-- *** POINT 1 *** Explicitly set the exported attribute to false. -->
        <service android:name=".PrivateStartService" android:exported="false"/>
        <!-- Private Service derived from IntentService class -->
        <!-- *** POINT 1 *** Explicitly set the exported attribute to false. -->
        <service android:name=".PrivateIntentService" android:exported="false"/>
    </application>
</manifest>

PrivateStartService.java

package org.jssec.android.service.privateservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class PrivateStartService extends Service {

    // The onCreate gets called only one time when the service starts.
    @Override
    public void onCreate() {
        Toast.makeText(this, "PrivateStartService - onCreate()", Toast.LENGTH_SHORT).show();
    }
    
    // The onStartCommand gets called each time after the startService gets called.
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // *** POINT 2 *** Handle the received intent carefully and securely,
        // even though the intent was sent from the same application.
        String param = intent.getStringExtra("PARAM");
        Toast.makeText(this,
        String.format("PrivateStartService¥nReceived param: ¥"%s¥"", param),
        Toast.LENGTH_LONG).show();
        return Service.START_NOT_STICKY;
    }
    
    // The onDestroy gets called only one time when the service stops.
    @Override
    public void onDestroy() {
        Toast.makeText(this, "PrivateStartService - onDestroy()", Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        // This service does not provide binding, so return null
        return null;
    }
}

Далее следует код активности для использования частного сервиса.

Основные моменты (использование сервиса): 4) Используйте явное намерение с указанным классом для вызова службы в том же приложении. 5) Поскольку целевой сервис находится в том же приложении, можно отправлять конфиденциальные данные. 6) Даже если данные поступают от службы в том же приложении, необходимо тщательно и безопасно обрабатывать полученные результаты.

PrivateUserActivity.java

package org.jssec.android.service.privateservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class PrivateUserActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.privateservice_activity);
    }
    
    // --- StartService control ---
    public void onStartServiceClick(View v) {
        Intent intent = new Intent(this, PrivateStartService.class);
        intent.putExtra("PARAM", "Sensitive information");
        startService(intent);
    }
    
    public void onStopServiceClick(View v) {
        doStopService();
    }
    
    @Override
    public ```
void onStop() {
    super.onStop();
    // Stop service if the service is running.
    doStopService();
}

private void doStopService() {
    // *** POINT 4 *** Use the explicit intent with class specified to call a service in the same application.
    Intent intent = new Intent(this, PrivateStartService.class);
    stopService(intent);
}

// --- IntentService control ---
public void onIntentServiceClick(View v) {
    // *** POINT 4 *** Use the explicit intent with class specified to call a service in the same application.
    Intent intent = new Intent(this, PrivateIntentService.class);
    // *** POINT 5 *** Sensitive information can be sent since the destination service is in the same application.
    intent.putExtra("PARAM", "Sensitive information");
    startService(intent);
}

Опубликовать ( 0 )

Вы можете оставить комментарий после Вход в систему

1
https://api.gitlife.ru/oschina-mirror/wizardforcel-android-app-sec-guidebook.git
git@api.gitlife.ru:oschina-mirror/wizardforcel-android-app-sec-guidebook.git
oschina-mirror
wizardforcel-android-app-sec-guidebook
wizardforcel-android-app-sec-guidebook
master