我正在使用服务运行的Android应用。该服务将从simcard获取您在后台的位置。我想使用闹钟管理器运行服务始终:每30秒或其他东西(不需要精确)。此外,当手机重新启动时,需要再次启动服务。
但是我无法让服务运行。这是我为这个问题编写的代码:
我在AndroidManifest文件中添加了权限:
<service android:enabled="true" android:name=".services.CountryService" />
<receiver android:name=".broadcasters.CountryUpdateReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
我写了一个广播接收器,它将在启动时启动服务。我需要在安装应用程序后添加一些可以启动服务的内容。
名为CountryUpdateReceiver的广播接收器:
public class CountryUpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
CountryService.acquireStaticLock(context);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent countryIntent = new Intent(context, CountryService.class);
PendingIntent countryService = PendingIntent.getService(context, 0, countryIntent, 0);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 10 * 1000, 10 * 1000, countryService);
}
}
最后我将服务本身称为CountryService:
public class CountryService extends WakefulIntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*/
public CountryService() {
super("CountryIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d("Service", "Test");
//android.os.Debug.waitForDebugger();
String country = getUserCountry(this);
Uri uri2 = Uri.parse(CountryProvider.CONTENT_URI + CountryProvider.COUNTRY_ISO_ADD);
getContentResolver().update(uri2, null, null, new String[] {"BE"});
//Intent broadcastIntent = new Intent("my-event");
// add data
//intent.putExtra("message", "data");
super.onHandleIntent(intent);
}
/**
* Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
* Origin: http://stackoverflow.com/questions/3659809/where-am-i-get-country/19415296#19415296
* @param context Context reference to get the TelephonyManager instance from
* @return country code or null
*/
public static String getUserCountry(Context context) {
try {
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final String simCountry = tm.getSimCountryIso();
if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
return simCountry.toLowerCase(Locale.US);
} else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
String networkCountry = tm.getNetworkCountryIso();
if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
return networkCountry.toLowerCase(Locale.US);
}
}
} catch (Exception e) {
}
return null;
}
服务本身从WakefulIntentService
(Gist)延伸。这是一个由其他人写的关于获取唤醒锁的课程。我跟着这个Example,因为我没有任何服务经验。
答案 0 :(得分:1)
向清单添加以下权限应该有所帮助
这些似乎没有添加到您的清单中。
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />