朋友们,您好我正在开发一款Battery android应用程序。关闭应用程序后,状态栏上显示电池电量(%)。我启动一个作为后台进程运行的服务类并放入一些代码。 Notificationservice.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));
}
});
}
当我按下运行应用程序正常运行但按下启动时服务按钮电池电量显示在状态栏上但它没有更改/更新它保持不变。朋友请帮帮忙,我该怎么办.... ???
答案 0 :(得分:0)
您需要从广播接收器启动服务或通知..只需注册广播以获得电池电量......以及来自接收器的onreceive()方法。通知或启动服务..