我有一個計時器,顯示剩下多少時間讓用戶再次播放。 我意識到服務可以爲我做到這一點,所以我創建一個與START_STICKY標籤單獨的過程。並使用Receiver爲了得到結果..這工作正常。 但是當我關閉應用服務將被重新啓動,一切從開始時間開始...爲什麼我的計時器在關閉應用程序後重置?
的問題是:如何防止重新啓動該服務或其他? 方法來解決這個問題?!
ty.regards。
我的活動:
public class MainActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onDestroy() {
super.onDestroy();;
}
public static void StartService(Context context,int globalTime,int localTime){
Intent i= new Intent(context,Services.class);
i.putExtra("value", localTime);
i.putExtra("value2", true);
context.startService(i);
}
}
我Reciver:
public class Reciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int defaultValue = -1;
Toast.makeText(context,String.valueOf(intent.getIntExtra("value", defaultValue), Toast.LENGTH_SHORT).show();
}
}
我的服務:
public class Services extends Service {
int id;
@Override
public void onCreate(){
alarm();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
id = startId;
maxTimerValue = mainIntent.getIntExtra("value", 0);
if(currentTimerValue < maxTimerValue){
currentTimerValue++;
BroadCatster();
}else{
currentTimerValue = 0
}
}
}
public void alarm(){
Intent i = new Intent(this, Services.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 0, 1000, pi);
}
public void BroadCatster(){
Intent intent = new Intent(this,Reciver.class);
intent.setAction("RECIVER_FILTER");
intent.putExtra("value", currentTimerValue);
this.sendBroadcast(intent);
}
}
}
MainFest
<receiver android:name="com.example.Reciver">
<intent-filter>
<action android:name="RECIVER_FILTER" />
</intent-filter>
</receiver>
<service
android:enabled="true"
android:exported="false"
android:name="com.example.Services"
android:label="@string/app_name"
android:process=":Service">
</service>
yes startForeground或創建Toast總是阻止服務在單獨進程中運行時重新啓動服務。你的想法是工作,但我不想顯示通知becaouse總是在用戶的神經:( –
這不會顯示通知,據我所知 – ljpv14
Oo ... omg .. w8 plz –