4.4.1.1 Создание/использование частного сервиса
Частный сервис — это сервис, который не может быть запущен другими приложениями, поэтому он является наиболее безопасным сервисом. Когда вы используете частный сервис, предназначенный только для использования в приложении, вам не нужно беспокоиться о том, что он будет случайно отправлен любому другому приложению, если вы явно намереваетесь использовать его таким образом.
Ниже приведён пример кода для использования сервисов типа startService
.
Основные моменты (создание сервиса):
false
.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 )