use*_*159 41 android intentservice
这是场景:我有一个WakefulBroadcastReceiver,它可以备份到网络计算机或云端.当我知道平板电脑可以访问局域网时,它将在半夜开始运行.备份将使用存储访问框架将数据存储到由实例化WakefulBroadcastReceiver的片段"拾取"的位置和文件.所以我需要能够访问ContentResolver,为此我需要上下文.
从我对文档的所有阅读中,这就是BroadcastReceiver的用途 - 一个潜在的长期运行任务,应该在后台完成,而不会发生太多其他事情. - 像备份一样.我还没有看到任何将所有内容放在一起的例子.
如何在IntentService中获取上下文?这是接收器和调度服务的片段.
public class BackupAlarmReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, BackupSchedulingService.class);
startWakefulService(context, service);
}
}
public class BackupSchedulingService extends IntentService {
public BackupSchedulingService() {
super("BackupSchedulingService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
// How to get the context - it was a parameter when
// creating the new IntentService class above?
}
}
Run Code Online (Sandbox Code Playgroud)
示例代码几乎完全遵循Android参考手册代码:
https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html
kle*_*erg 32
打电话吧 getApplicationContext()
小智 9
您可以在onStartCommand()函数中获取上下文.
public class ExampleService extends IntentService {
private Context mContext;
public ExampleService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mContext = getApplicationContext();
return super.onStartCommand(intent, flags, startId);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37711 次 |
| 最近记录: |