所以我有一个单击按钮时启动的服务。当服务启动时,我禁用了单击的按钮,但是我想在服务完成后再次启用它。如果我在服务类中创建一个调用类的实例,我会得到一个空指针异常。我不知道如何再次启用该按钮。如果我在调用“stopService()”之后立即执行此操作,则按钮将保持启用状态。请帮忙。谢谢你们。
代码 - >服务类
package com.project.llb;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class SetupTimer extends Service
{
Handler handler;
runGraphics runG;
int timerCount = 0;
@Override
public IBinder onBind(Intent intent)
{
return null;
}//end onBind function
@Override
public void onCreate()
{
super.onCreate();
handler = new Handler();
timerCount++;
handler.postDelayed(runnable, 1000);
}//end onCreate function
private Runnable runnable = new Runnable()
{
public void run()
{
timerCount++;
if (timerCount < 3)
{
handler.postDelayed(runnable, 1000);
}//end if
else
{
runG.polarCap1.setEnabled(true); //this will not work
handler.removeCallbacks(runnable);
}//end else
}//end run function
};//end runnable
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return Service.START_NOT_STICKY;
}//end onStartCommand function
}//end SetupTimer class
这是我在调用类中的按钮函数:
polarCap1 = (ImageButton) findViewById(R.id.polarCapButton1);
polarCap1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//button cannot be clicked
polarCap1.setEnabled(false);
//start service for timer
startService(new Intent(runGraphics.this, SetupTimer.class));
//stop service for timer
stopService(new Intent(runGraphics.this, SetupTimer.class));
//button can be clicked again
//polarCap1.setEnabled(true);
}//end onClick function
});//end setOnClickListener
这是我的logcat:
05-23 09:58:06.986: E/AndroidRuntime(31852): FATAL EXCEPTION: main
05-23 09:58:06.986: E/AndroidRuntime(31852): java.lang.NullPointerException
05-23 09:58:06.986: E/AndroidRuntime(31852): at com.project.llb.SetupTimer$1.run(SetupTimer.java:64)
05-23 09:58:06.986: E/AndroidRuntime(31852): at android.os.Handler.handleCallback(Handler.java:587)
05-23 09:58:06.986: E/AndroidRuntime(31852): at android.os.Handler.dispatchMessage(Handler.java:92)
05-23 09:58:06.986: E/AndroidRuntime(31852): at android.os.Looper.loop(Looper.java:130)
05-23 09:58:06.986: E/AndroidRuntime(31852): at android.app.ActivityThread.main(ActivityThread.java:3806)
05-23 09:58:06.986: E/AndroidRuntime(31852): at java.lang.reflect.Method.invokeNative(Native Method)
05-23 09:58:06.986: E/AndroidRuntime(31852): at java.lang.reflect.Method.invoke(Method.java:507)
05-23 09:58:06.986: E/AndroidRuntime(31852): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-23 09:58:06.986: E/AndroidRuntime(31852): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-23 09:58:06.986: E/AndroidRuntime(31852): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
使用本地广播发送按钮状态。