Joa*_*ins 4 service android background android-asynctask android-activity
目前,当我的应用程序(活动)处于前台时,我只能将数据发送到服务器。至少在 4.1.3 中会发生这种情况,因为 android SO 暂停了应用程序或停止了它。
即使活动在后台,我也需要一直发送数据。
实现这一目标的最佳方法是什么。Asynctask 不是一个好的答案,因为我想定期发送数据。不止一次。我已经使用 asynctasks 作为将数据发送到服务器的一种方式,我需要的是与活动一起运行但不会被 SO 停止的东西。
编辑:
我使用以下代码收到此错误。
04-03 13:55:28.804: E/AndroidRuntime(1165): java.lang.RuntimeException: Unable to instantiate receiver main.inSituApp.BootCompletedIntentReceiver: java.lang.ClassNotFoundException: main.inSituApp.BootCompletedIntentReceiver
Run Code Online (Sandbox Code Playgroud)
谁能告诉我那个错误是什么意思?我没有那个接收器的类,但如果我在清单中注册它,我就不需要它了。
你可以写services
和AlarmManager
这样做。只需在服务中注册您的应用程序并调用alarmMangaer.setRepeat()
方法来启动您的服务器端代码或您想在onStart()
服务方法中执行的任何其他操作
public class MyService extends Service{
Calendar cur_cal = Calendar.getInstance();
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(getApplicationContext(),
0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
cur_cal.setTimeInMillis(System.currentTimeMillis());
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cur_cal.getTimeInMillis(),
60 * 1000*3, pintent);
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
// your code for background process
}
}
Run Code Online (Sandbox Code Playgroud)
在 AndroidManifest.xml 中添加这个
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<service
android:name="com.yourpackage.MyService"
android:enabled="true" />
<receiver android:name=".BootCompletedIntentReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
编辑: BootCompletedIntentReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootCompletedIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent pushIntent = new Intent(context, MyService.class);
context.startService(pushIntent);
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6520 次 |
最近记录: |