gpt4 book ai didi

java - 当应用程序重新打开和关闭时 Android 服务停止

转载 作者:太空宇宙 更新时间:2023-11-04 14:43:24 25 4
gpt4 key购买 nike

我正在尝试了解 Android 服务的工作原理。

所以我创建了一个带有 Activity 和服务的简单应用程序,代码如下:

MainActivity.xml:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service"
android:id="@+id/buttonStart"
android:layout_marginTop="60dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="startButtonClickHandler"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service"
android:id="@+id/buttonStop"
android:layout_below="@+id/buttonStart"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:enabled="false"
android:onClick="stopButtonClickHandler" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:text="Counter is: 0" />

</RelativeLayout>

MainActivity.java:

package com.example.wellsaid.provaservice;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;


public class MainActivity extends Activity {

Button btn_stop = null;
Button btn_start = null;

/*---------------------------- CODICE NUOVO -----------------------------*/
private class MyReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context arg0, Intent arg1) {
int datapassed = arg1.getIntExtra("count", 0);
TextView text = (TextView) findViewById(R.id.textView);
text.setText("Counter is: " + datapassed);
}

}

MyReceiver myreceiver = null;
/*---------------------------------------------------------------------*/

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_stop = (Button) findViewById(R.id.buttonStop);
btn_start = (Button) findViewById(R.id.buttonStart);
if(ExampleService.isRunning()){
btn_stop.setEnabled(true);
btn_start.setText("Send request");
Intent intent = new Intent(this, ExampleService.class);
intent.putExtra("count",0);
startService(intent);
}

/*--------------------- CODICE NUOVO -------------------------------*/
myreceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ExampleService.RETURN_COUNTER);
registerReceiver(myreceiver, intentFilter);
/*------------------------------------------------------------------*/
}

public void startButtonClickHandler(View v){
if(!btn_stop.isEnabled()) {
btn_stop.setEnabled(true);
btn_start.setText("Send request");
}
Intent intent = new Intent(this, ExampleService.class);
intent.putExtra("count",0);
startService(intent);
}

public void stopButtonClickHandler(View v){
Intent intent = new Intent(this, ExampleService.class);
stopService(intent);
btn_start.setText("Start Service");
btn_stop.setEnabled(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}

@Override
protected void onStop() {
// TODO Auto-generated method stub
unregisterReceiver(myreceiver);
super.onStop();
}

}

示例服务.java

package com.example.wellsaid.provaservice;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;


public class ExampleService extends Service {

/*--------------------- CODICE NUOVO-------------------------------*/
final static String RETURN_COUNTER = "RETURN_COUNTER";
/*----------------------------------------------------------------*/

@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent intent = new Intent(this, ExampleService.class);
intent.putExtra("count",thread.getCounter());
startService(intent);
}

@Override
public IBinder onBind(Intent intent) {
return null;
}

ExampleThread thread = null;
private static boolean running = false;

public static boolean isRunning() { return running; }

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
running = true;
if(thread == null) {
int counter = intent.getExtras().getInt("count");
thread = new ExampleThread(counter);
thread.start();
}
else{
/*-----------------------CODICE NUOVO ----------------------*/
Intent send = new Intent();
send.setAction(RETURN_COUNTER);
send.putExtra("count",thread.getCounter());
sendBroadcast(send);
/*----------------------------------------------------------*/
}
return startId;
}

@Override
public void onDestroy() {
running = false;
thread.kill();
super.onDestroy();
}

private class ExampleThread extends Thread {

boolean stopped;
int counter = 0;

public ExampleThread(int counter){
this.counter = counter;
}

public void start(){
stopped = false;
super.start();
}

public int getCounter(){ return counter; }

public void kill(){
stopped = true;
}

public void run(){
while(!stopped) {
try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
counter++;
Log.i("Service", "Counter is: " + counter);
}
}
}
}

这就是我的 list :

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wellsaid.provaservice" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<service android:name=".ExampleService" />

</application>

</manifest>

我尝试过:1)打开应用程序,使用开始按钮启动服务,然后使用另一个按钮停止它。一切OK 2)打开应用程序,启动服务并关闭应用程序。一切正常(服务仍在运行) 3) 打开应用程序,启动服务,重新打开应用程序并获取计数器值。一切OK 4)打开应用程序,启动服务,关闭应用程序,重新打开应用程序并停止服务。一切OK(关闭后还要重新启动服务)当我打开、启动服务、关闭应用程序、重新打开以检查计数器编号,然后再次关闭应用程序时,问题就会出现,一段时间后,服务停止,logcat 中没有消息:(在我的 Android 设备上的应用程序管理中,我可以看到我的应用程序处于重新启动状态,并且在输入很长一段时间后,它会重新启动,然后再次停止,不断地......我已经在三星 Galaxy Express Stock (Android 4.1.2) 和三星 Galaxy Tab 2 10.1 上进行了测试,并安装了氰基mod 10.1.3 (Android 4.2.2)

最佳答案

您读过https://developer.android.com/reference/android/app/Service.html吗? ?

请注意以下事项:

For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them.

来自 START_STICKY 文档:

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.

关于java - 当应用程序重新打开和关闭时 Android 服务停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24713247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com