这是我的服务类代码,这里的previous_network_type是全局静态变量,它不是在oncreate()或onstartcommand()函数中初始化的,也不是来自创建函数的活动,为什么有任何帮助?每当我使用它时,它给我0值,它应该在启动此服务后给我10但返回0.更清楚
首先MyService有previous_network_type变量我想在oncreate或oncommand函数中为它赋值 我将在另一个广播接收器类中使用它 并且您知道广播接收器仅在事件发生时运行,因此当特定事件发生时我想要访问此值的是
public class MyService extends Service {
static int previous_network_type=0;
public void onCreate() {
previous_network_type=10;
};
public int onStartCommand(Intent intent, int flags, int startId) {
previous_network_type=10;
return Service.START_STICKY;
}
}
和其他类的代码(广播接收器如下)
public void onReceive(Context context, Intent intent)
{
MyService.current_network_type=MyService.previous_network_type;
}
答案 0 :(得分:0)
public class MainActivity extends Activity {
Intent i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i=new Intent(this,MyService.class);
startService(i);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();;
stopService(i);
}
}
public class MyService extends Service {
static int previous_network_type=0;
public void onCreate() {
previous_network_type=10;
};
public int onStartCommand(Intent intent, int flags, int startId) {
previous_network_type=10;
Log.e("check","Value"+previous_network_type);
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
检查一下你是否在Android.manifest.xml中定义了服务
<service android:name="com.example.kuchbhi.MyService"
></service>
答案 1 :(得分:0)
确保在创建/启动服务后访问该值。 尝试调试。