1
您好朋友我正在開發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));
}
});
}
當我按運行的應用程序正常運行,但是當我按下啓動服務按鈕電池電量顯示在狀態欄,但它不會改變/更新它保持不變。朋友請幫忙,我該怎麼辦....?
試試這個一次.. – Meenal 2014-10-26 14:13:28
我獲得電池電量並啓動一項服務,顯示電池電量的通知。但它沒有得到更新(就像我開始服務在25℅它顯示通知您的電池電量是25℅它不會更新/更改) – 2014-10-27 12:17:15
您必須更新通知continuusloy – Meenal 2014-10-27 12:25:06