我有MainActivity和自定义服务名称BatteryService。在此服务中,我正在使用电池级别并对其进行一些处理。这是此服务类的示例代码。
public class BatteryService extends Service {
Context context ;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
context = this;
Log.v("Service Started : ", "" );
BatteryService.this.registerReceiver(brodcastReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
protected BroadcastReceiver brodcastReceiver = new BroadcastReceiver() {
int intlevel;
MediaPlayer mediaPlayer;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
intlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
String dtr;
dtr = String.valueOf(intlevel);
Toast.makeText(context, dtr, Toast.LENGTH_LONG).show();
try {
intlevel = intent.getIntExtra("level", 0);
Log.v("Battery level is : ", "" + dtr);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
String strStatus;
if ((status == BatteryManager.BATTERY_STATUS_CHARGING) && (intlevel >= 90)) {
Toast.makeText(context, "charging", Toast.LENGTH_LONG).show();
mediaPlayer = MediaPlayer.create(BatteryService.this, R.raw.alarmsound);
mediaPlayer.start();
}
if ((status == BatteryManager.BATTERY_STATUS_DISCHARGING) && (intlevel >= 99))
{
mediaPlayer.stop();
}
}
};
}
在主要活动中我有按钮,然后点击该按钮我就是 启动服务,如:
public class MainActivity extends Activity {
Button btnStart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.btn_startService);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v("Starting service","On Button click");
Intent intent = new Intent(MainActivity.this, BatteryService.class);
startService(intent);
}
});
}
}
并以下列方式在Manifest中声明
机器人:名称=" com.brokenfloorstudios.eyebattery.BatteryService" />
答案 0 :(得分:1)
我发布这个答案,以便如果有人遇到我遇到的同样问题。这是一个小问题。当我创建自己的自定义服务时,我在Application Manifest文件的结束标记下面声明它。 它应该在manifest中的应用程序标记中声明。由于我没有在Logcat中获得任何错误或异常,因此需要时间来弄清楚它。
答案 1 :(得分:0)
试试这个
Intent a = new Intent();
a.setAction (" *** insert service name here**");
StartService(a);
我通常会将清单文件中的字符串复制并粘贴到我的活动中,因为它很容易造成拼写错误