你好朋友我正在开发一个 Battery android 应用程序。关闭应用程序后在状态栏上显示电池电量(%)。我启动了一个作为后台进程运行的服务类并放置了一些代码。通知服务.java
public void onCreate(){
super.onCreate();
IntentFilter filter= new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus= getApplicationContext().registerReceiver(null, filter);
int status= batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
batteryLevel= String.valueOf(status);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//make the toast message
Toast.makeText(this, "Service Started"+batteryLevel+"%", Toast.LENGTH_LONG).show();
//show the notification on status bar
NotificationManager nm=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent2= new Intent(this, MainActivity.class);
PendingIntent pendingIntent= PendingIntent.getActivity(getApplicationContext(), 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mbuilder= new
NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Battery Level: "+batteryLevel+"%")
.setContentText("Battery Level: "+batteryLevel+"%")
.setContentIntent(pendingIntent);
nm.notify(notificationID, mbuilder.build());
return START_STICKY;
}
@Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(getApplicationContext(), "service Destroy", Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
在 MainActivity.java
rotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1= (Button) findViewById(R.id.button1);
b2= (Button) findViewById(R.id.button2);
tv= (TextView) findViewById(R.id.textView1);
createListener();
}
private void createListener() {
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), Notificationservice.class));
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Notificationservice.class));
}
});
}
当我按下运行应用程序时,应用程序正常运行,但当我按下启动服务按钮时,状态栏上会显示电池电量,但它不会更改/更新,它保持不变。请朋友帮忙,我该怎么办......???