我想创建一个服务,即使我运行另一个应用程序,也会不断更新Textview。如果按下停止按钮,服务将停止。在下面的代码中,我使用了服务和BroadcastReceiver的组合,但是如果我更改应用程序,服务不会更新TextView。
代码:
服务
public class ChronometerService extends Service
{
public static final String BROADCAST_ACTION = "com.example.test";
private final Handler handler = new Handler();
private Intent intent = null;
int counter = 0;
@Override
public void onCreate()
{
super.onCreate();
intent = new Intent( BROADCAST_ACTION );
}
@Override
public void onStart( Intent intent, int startId )
{
//handler.removeCallbacks( sendUpdatesToUI );
handler.postDelayed( sendUpdatesToUI, 1000 );
}
@Override
public IBinder onBind( Intent intent )
{
return null;
}
private Runnable sendUpdatesToUI = new Runnable()
{
@Override
public void run()
{
DisplayLoggingInfo();
handler.postDelayed( this, 1000 );
}
};
private void DisplayLoggingInfo()
{
counter += 1;
//chrono.start();
intent.putExtra( "TIME", String.valueOf(counter) );
sendBroadcast( intent );
}
@Override
public void onDestroy()
{
//chrono.stop();
//chrono.setBase( SystemClock.elapsedRealtime() );
handler.removeCallbacks( sendUpdatesToUI );
super.onDestroy();
}
}
活动
public class MainActivity extends Activity
{
public static TextView chronometer1 = null;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent( MainActivity.this, ChronometerService.class );
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
{
@Override
public void onReceive( Context context, Intent intent )
{
updateUI( intent );
}
};
private void updateUI( Intent intent )
{
String time = intent.getStringExtra( "TIME" );
chronometer1 = ( TextView ) findViewById( R.id.chronometer1 );
chronometer1.setText( time );
}
public void start( View v )
{
startService( intent );
registerReceiver(broadcastReceiver, new IntentFilter( ChronometerService.BROADCAST_ACTION ) );
}
public void stop( View v )
{
unregisterReceiver( broadcastReceiver );
stopService( intent );
}
}
答案 0 :(得分:0)
我找到了答案: 当服务运行并且我不希望它被操作系统杀死时,我必须使用startForeground(int id,Notification notification)方法。
当服务完成正在进行的操作并且可以被操作系统杀死时,请调用stopForeground(boolean removeNotification)。 " startForeground"需要通知作为参数,因为每个前台服务必须显示通知,以便用户意识到它。
还有助于在清单文件中的服务声明中设置属性:
android:process =":这里有一些名字"