手机系统设置里会有“帐户”一项功能,任何第三方APP都可以通过此功能将数据在一定时间内同步到服务器中去。系统在将APP帐户同步时,会将未启动的APP进程拉活。
https://github.com/googlesamples/android-BasicSyncAdapter google关于账户拉活的相关demo
首先,我们要有一个账户服务
public class AuthenticationService extends Service {
private AccountAuthenticator accountAuthenticator;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return accountAuthenticator.getIBinder();
}
@Override
public void onCreate() {
super.onCreate();
accountAuthenticator = new AccountAuthenticator(this);
}
static class AccountAuthenticator extends AbstractAccountAuthenticator {
public AccountAuthenticator(Context context) {
super(context);
}
@Override
public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) {
return null;
}
@Override
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType,
String authTokenType, String[] requiredFeatures, Bundle options)
throws NetworkErrorException {
return null;
}
@Override
public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account,
Bundle options) throws NetworkErrorException {
return null;
}
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String
authTokenType, Bundle options) throws NetworkErrorException {
return null;
}
@Override
public String getAuthTokenLabel(String authTokenType) {
return null;
}
@Override
public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account,
String authTokenType, Bundle options) throws
NetworkErrorException {
return null;
}
@Override
public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account,
String[] features) throws NetworkErrorException {
return null;
}
}
}
该服务由系统启动,不需要手动去bind,同时,我们还需要到清单文件中去注册该服务
<!--账户服务-->
<service android:name=".account.AuthenticationService">
<intent-filter>
<action android:name="android.accounts.AccountAuthenticator" />
</intent-filter>
<meta-data
android:name="android.accounts.AccountAuthenticator"
android:resource="@xml/accountauthenticator" />
</service>
注意上述的action必须为“android.accounts.AccountAuthenticator”,否则系统无法启动该服务,
另外我们的meta-data中需要制定一个resource
<?xml version="1.0" encoding="utf-8"?>
<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android"
android:accountType="com.dongnao.daemon.account"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" />
上述的icon代表在手机账户下显示的图标。label为手机账户下显示的名称
接下来我们允许一下我们的app,然后打开设计设置页里面的账户,便能看到如图这代表我们的app已经拥有了账号服务,拥有了账号服务之后,我们再来试图往里面添加一个账号试试
public class AccountHelper {
private static final String TAG = "AccountHelper";
public static final String ACCOUNT_TYPE = "com.dongnao.daemon.account";
public static void addAccount(Context context) {
AccountManager am = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
//获得此类型的账户
Account[] accounts = am.getAccountsByType(ACCOUNT_TYPE);
if (accounts.length > 0) {
Log.e(TAG, "账户已存在");
return;
}
//给这个账户类型添加一个账户
Account dongnao = new Account("dongnao", ACCOUNT_TYPE);
am.addAccountExplicitly(dongnao, "dn", new Bundle());
}
/**
* 设置 账户自动同步
*/
public static void autoSync() {
Account dongnao = new Account("dongnao", ACCOUNT_TYPE);
//设置同步
ContentResolver.setIsSyncable(dongnao, "com.dongnao.daemon.provider", 1);
//自动同步
ContentResolver.setSyncAutomatically(dongnao, "com.dongnao.daemon.provider", true);
//设置同步周期
ContentResolver.addPeriodicSync(dongnao, "com.dongnao.daemon.provider", new Bundle(), 1);
}
}
通过addAccount,我们向系统中添加一个账户,增加后的效果为当然,上述向系统添加账户的方式需要获取相应的权限
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
添加完账户之后,我们需要来进行账户同步,这个时候我们还需要创建一个service来进行账户同步
public class SyncService extends Service {
SyncAdapter syncAdapter;
private static final String TAG = "SyncService";
@Nullable
@Override
public IBinder onBind(Intent intent) {
return syncAdapter.getSyncAdapterBinder();
}
@Override
public void onCreate() {
super.onCreate();
syncAdapter = new SyncAdapter(getApplicationContext(), true);
}
static class SyncAdapter extends AbstractThreadedSyncAdapter {
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
Log.e(TAG,"同步账户");
//与互联网 或者 本地数据库同步账户
}
}
}
该service同样有系统调用,系统在执行账户同步到时候会获取ibinder,而同步数据则在onPerformSync中执行,在onPerformSync当中我们可与编写同步代码,当然,我们本节内容主要是为了
让系统拉活app,所以可以不需要编写同步代码;
我们还需要在AndroidManifest中注册该service
<service android:name=".account.SyncService">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="@xml/sync_adapter" />
</service>
<provider
android:name=".account.SyncProvider"
android:authorities="com.dongnao.daemon.provider" />
action必须为”android.content.SyncAdapter“,否则系统无法启动服务,另外也必须声明resource
<?xml version="1.0" encoding="utf-8"?>
<sync-adapter xmlns:android="http://schemas.android.com/apk/res/android"
android:accountType="com.dongnao.daemon.account"
android:contentAuthority="com.dongnao.daemon.provider"
android:allowParallelSyncs="false"
android:isAlwaysSyncable="true"
android:userVisible="false"/>
<!--contentAuthority 系统在进行账户同步的时候会查找 此auth的ContentProvider-->
<!-- allowParallelSyncs 允许多个同步-->
public class SyncProvider extends ContentProvider {
@Override
public boolean onCreate() {
return false;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String
selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
return null;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[]
selectionArgs) {
return 0;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}
}
我们接下来再设置一下同步周期并设置自动同步
/**
* 设置 账户自动同步
*/
public static void autoSync() {
Account dongnao = new Account("dongnao", ACCOUNT_TYPE);
//设置同步
ContentResolver.setIsSyncable(dongnao, "com.dongnao.daemon.provider", 1);
//自动同步
ContentResolver.setSyncAutomatically(dongnao, "com.dongnao.daemon.provider", true);
//设置同步周期
ContentResolver.addPeriodicSync(dongnao, "com.dongnao.daemon.provider", new Bundle(), 1);
}
通过系统的账户同步功能来进行拉活算是一种比较可靠的方式,但是缺点就是拉活周期无法把控,不知道过多久拉活一次