我用android studio开发应用程序 我有一个连接网页并读取它的服务 如果网页包含"更新"然后程序创建一个Toast消息。服务每3秒钟完成一次。 它运作良好但在20-25分钟后服务停止工作 我该如何解决呢?
答案 0 :(得分:0)
破坏你的服务:
@Override
public void onDestroy() {
super.onDestroy();
Intent broadcastIntent = new Intent(".RestartService");
sendBroadcast(broadcastIntent);
}
在你的清单中添加一个接收器:
<receiver
android:name=".ServiceReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped">
<intent-filter>
<action android:name=".RestartService"/>
</intent-filter>
</receiver>
然后,使用以下代码创建名为ServiceReceiver.java的Java文件:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, BackgroundService.class));
}
}
** BackgroundService是服务类的名称。此代码将帮助您在操作系统或用户关闭服务时自动启动服务。
答案 1 :(得分:0)
在你的清单中添加一个接收器:
<receiver android:name="com.example.admin.apptech_nation.service.AlarmManagerBroadcastReceiver"/>
在您的MainActivity中,您需要setRepiting Brodcast
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent myIntent = new Intent(mContext, AlarmManagerBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 60); // first time
long frequency = 60 * 50; // in ms
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, pendingIntent);
}
在你的BroadcastReciver中
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver{
Context Mcontext;
@Override
public void onReceive(Context context, Intent intent) {
Mcontext = context;
}