传递从服务到活动的价值

时间:2014-07-02 18:35:16

标签: android

我的Android项目中存在此代码的一些问题。我需要从后台工作的服务中获取电池百分比级别,当用户打开应用程序时,我需要将该百分比传递给应用程序的主要活动。在服务中我正确地拿走电池百分比并且我能够在祝酒词中看到它,但是当我尝试将号码发送到活动时我总是有0.这是我的服务的代码

public class MyService extends Service {

private final IBinder mBinder = new LocalBinder();

public class LocalBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

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

public int b=0, livello;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent intent) {
        int level = intent.getIntExtra("level", 0);
        b=level;
        if(b!=livello&&b!=0) {
            livello=b;
        }
    }
};

//prendo il livello senza aspettare il broadcast
public float getMyBatteryLevel() {
    Intent batteryIntent = this.getApplicationContext().registerReceiver(null,
    new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    return batteryIntent.getIntExtra("level", -1);
}

@Override
public void onCreate() {
       super.onCreate();
       float a = getMyBatteryLevel();
       livello = (int) a;

       registerReceiver(this.mBatInfoReceiver, 
               new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

       Toast.makeText(getApplicationContext(), "Service Created "+livello,1).show();
}


@Override
public void onDestroy() {
       Toast.makeText(getApplicationContext(), "Service Destroy",1).show();
       super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
       Toast.makeText(getApplicationContext(), "Service Working",1).show();
       return super.onStartCommand(intent, flags, startId);
}


//funzione che uso solo per passare il livello all'altro file java
public int getBatteryLevel() {
    return livello;
}

}

这是活动

的代码
public class SaveBattery extends Activity {

MyService mService = new MyService();
boolean mBound;

public int livello=10;
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tv  = (TextView) findViewById (R.id.tv);


    //se il service non è attivo lo lancio
    if (isMyServiceRunning(MyService.class) == false)
        startService(new Intent(this, MyService.class));


    Intent intent = new Intent(this, MyService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);


    livello = mService.getBatteryLevel();

    tv.setText(""+livello);


}


//verifico se il service è attivo
private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}



private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className,
            IBinder service) {
        Toast.makeText(SaveBattery.this, "Service is connected", 1000).show();
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {

        Toast.makeText(SaveBattery.this, "Service is disconnected", 1000).show();
        mBound = false;
    }
};

}

任何人都可以帮助我?

2 个答案:

答案 0 :(得分:0)

尝试移动livello = mService.getBatteryLevel();在onServiceConnected回调中。

答案 1 :(得分:0)

我更喜欢通过广播消息在“服务活动”中接收消息。为此需要在活动(SaveBattery)上创建和注册广播接收器,并从服务发送电池电平作为广播消息。

我更改了代码,在Activity中创建了一个新的广播接收器,并将Activity的电池电量设置为已检查。

如果这种方法适合你,你可以使用它。

的活动:

public class SaveBattery extends Activity {

MyService mService = new MyService();
boolean mBound;

public int livello=10;

TextView tv;
static final String BROADCAST_BATTERY_LEVEL = "battery_level";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tv  = (TextView) findViewById (R.id.tv);


    //se il service non è attivo lo lancio
    if (isMyServiceRunning(MyService.class) == false)
        startService(new Intent(this, MyService.class));


    Intent intent = new Intent(this, MyService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);


    livello = mService.getBatteryLevel();

    tv.setText(""+livello);


    // Registering BroadcastReceiver for receiving battery level from MyService
    LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(new Receiver(), new IntentFilter(BROADCAST_BATTERY_LEVEL)); 
}

// Defining a BroadcastReceiver
private class Receiver extends BroadcastReceiver{
    String msg;
    @Override
    public void onReceive(Context context, Intent intent) {     
        tv.setText(String.valueOf(intent.getIntExtra("batterylevel", 0)));
    }
}

//verifico se il service è attivo
private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className,
            IBinder service) {
        Toast.makeText(SaveBattery.this, "Service is connected", 1000).show();
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {

        Toast.makeText(SaveBattery.this, "Service is disconnected", 1000).show();
        mBound = false;
    }
};
}

服务:

public class MyService extends Service {

static final String BROADCAST_BATTERY_LEVEL = "battery_level";

private final IBinder mBinder = new LocalBinder();

public class LocalBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

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

public int b=0, livello;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent intent) {
        int level = intent.getIntExtra("level", 0);
        // send battery level to the Activity (SaveBattery)
        sendBroadcast(level);

        b=level;
        if(b!=livello&&b!=0) {
            livello=b;
        }
    }
};

//Method to send broadcast Message to Activity
private void sendBroadcast (int i) {
    Intent broadcastIntent = new Intent(BROADCAST_BATTERY_LEVEL);
    // Attaching data to the intent
    broadcastIntent.putExtra("batterylevel", i);
    // Sending the broadcast
    LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent);
}


//prendo il livello senza aspettare il broadcast
public float getMyBatteryLevel() {
    Intent batteryIntent = this.getApplicationContext().registerReceiver(null,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    return batteryIntent.getIntExtra("level", -1);
}

@Override
public void onCreate() {
    super.onCreate();
    //float a = getMyBatteryLevel();
    //livello = (int) a;

    registerReceiver(this.mBatInfoReceiver, 
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    Toast.makeText(getApplicationContext(), "Service Created "+livello,1).show();

}


@Override
public void onDestroy() {
    Toast.makeText(getApplicationContext(), "Service Destroy",1).show();
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(getApplicationContext(), "Service Working",1).show();


    return super.onStartCommand(intent, flags, startId);
}


//funzione che uso solo per passare il livello all'altro file java
public int getBatteryLevel() {
    return livello;
}
}