Я пишу простое приложение для секундомера и обратного отсчета.Различные части приложения представлены вкладками.Поэтому моя основная деятельность выглядит так:
@SuppressWarnings("deprecation")
public class ITimeActivity extends TabActivity {
StopwatchInterface service;
Intent mServiceIntent;
RemoteServiceConnection conn;
class RemoteServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName name, IBinder binder) {
service = StopwatchInterface.Stub.asInterface((IBinder) binder);
}
public void onServiceDisconnected(ComponentName name) {
service = null;
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Service starten
Intent i = new Intent();
i.setClassName("com.BlubBlub.iTime", "com.BlubBlub.iTime.RemoteService");
startService(new Intent(this, StopwatchService.class));
final TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
intent = new Intent().setClass(this, Tab1.class);
spec = tabHost.newTabSpec("tab1").setIndicator(getString(R.string.wecker)).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, Tab2.class);
spec = tabHost.newTabSpec("tab2").setIndicator(getString(R.string.stoppuhr)).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, Tab3.class);
spec = tabHost.newTabSpec("tab3").setIndicator(getString(R.string.countdown)).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, Tab4.class);
spec = tabHost.newTabSpec("tab4").setIndicator(getString(R.string.weltzeit)).setContent(intent);
tabHost.addTab(spec);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if(prefs.getString("tabstart", "0") == "4") {
SharedPreferences myPrefs = getSharedPreferences("iTime.settings", MODE_WORLD_READABLE);
tabHost.setCurrentTab(myPrefs.getInt("start", 0));
}
else {
tabHost.setCurrentTab(Integer.parseInt(prefs.getString("tabstart", "0")));
}
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String arg0) {
SharedPreferences myPrefs = getSharedPreferences("iTime.settings", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt("start", getTabHost().getCurrentTab());
prefsEditor.commit();
}
});
}
public void onDestroy() {
super.onDestroy();
unbindService(conn);
try {
if(service.getServiceState() == false) {
Intent i = new Intent();
i.setClassName("com.BlubBlub.iTime", "com.BlubBlub.iTime.RemoteService");
stopService(i);
}
} catch (RemoteException re) {
}
}
}
В этом классе я создаю сервис, который хорошо работает.Теперь давайте посмотрим на сам сервис.Сначала файл помощи:
interface StopwatchInterface {
boolean getServiceState();
long getElapsed();
void setStartStopwatch(long i);
void startStop();
void stopStop();
void setRefreshStopwatch(int j);
}
, а теперь соответствующая Java-часть службы:
public class StopwatchService extends Service {
public IBinder onBind(Intent intent) {
return myStopwatchServiceStub;
}
public boolean onUnbind(Intent intent) {
return false;
}
public int onStartCommand(Intent intent, int param1, int param2) {
return 0;
}
private StopwatchInterface.Stub myStopwatchServiceStub = new StopwatchInterface.Stub() {
public boolean getServiceState() throws RemoteException {
return running;
}
public long getElapsed() {
return elapsedTime;
}
public void setStartStopwatch(long i) {
startStopwatch = i;
}
public void startStop() {
mHandler1.removeCallbacks(stopwatch);
mHandler1.postDelayed(stopwatch, 0);
stopwatchrunning = true;
running = true;
}
public void stopStop() {
mHandler1.removeCallbacks(stopwatch);
stopwatchrunning = false;
if(countdownrunning == false) {
running = false;
}
}
public void setRefreshStopwatch(int i) {
refreshStopwatch = i;
}
};
}
И, наконец, соответствующая часть действия секундомера:
public class Tab2 extends Activity {
StopwatchInterface service;
Intent mServiceIntent;
RemoteServiceConnection conn;
class RemoteServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName name, IBinder binder) {
service = StopwatchInterface.Stub.asInterface((IBinder) binder);
}
public void onServiceDisconnected(ComponentName name) {
service = null;
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stoppuhr);
}
public void onResume() {
super.onResume();
mServiceIntent = new Intent();
mServiceIntent.setClassName("com.BlubBlub.iTime", "com.BlubBlub.iTime.RemoteService");
conn = new RemoteServiceConnection();
bindService(mServiceIntent, conn, Context.BIND_AUTO_CREATE);
try {
service.setRefreshStopwatch(1);
} catch (RemoteException re) {
}
REFRESH_RATE = 1;
}
}
Когда я запускаю свое приложение, фокус автоматически устанавливается на класс Tab2.Но в методе onResume я получаю исключение NullPointerException в строке
service.setRefreshStopwatch(1);
Таким образом, я предполагаю, что служба неправильно связана.
Что мне нужно для моего приложения?У меня есть секундомер и обратный отсчет времени, когда таймер может быть запущен отдельно.Я хочу, чтобы время запускалось, даже если приложение закрыто, поэтому мне нужен сервис для запуска двух таймеров.Но я не могу связать два вида деятельности с сервисом!Что я делаю не так?
Заранее спасибо Flo