Android Studio 之 启动和停止服务
16lz
2021-01-23
运行截图
MainActivity.java
运行前
package csdn.example.com.pushmessage;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import csdn.example.com.pushmessage.ServiceTest.MyService;public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button startService = (Button) findViewById(R.id.start_service); Button stopService = (Button) findViewById(R.id.stop_service); startService.setOnClickListener(this); stopService.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.start_service: Intent startIntent = new Intent(this, MyService.class); startService(startIntent);//启动服务 break; case R.id.stop_service: Intent stopIntent = new Intent(this,MyService.class); stopService(stopIntent);//停止服务 break; default: break; } }}
停止服务后运行截图
截图MyService.java
package csdn.example.com.pushmessage.ServiceTest;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class MyService extends Service { public MyService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } @Override public void onCreate() { super.onCreate(); Log.d("MyService","onCreate executed"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("MyService","onStartCommand executed"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d("MyService","onDestroy executed"); }}
清单文件 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="csdn.example.com.pushmessage"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> intent-filter> activity> <service android:name=".ServiceTest.MyService" android:enabled="true" android:exported="true">service> application>manifest>
更多相关文章
- Android上SD卡图片的标准缓存方法
- Android实现图片预览浏览功能
- android 将图片转换成二进制,再讲二进制转换成图片 可用于编码加
- android缩放大图片加载
- RadioButton使用的过程中Text文本和图片显示的问题
- android 使用handler更新ui,使用与原理分析详解(附上代码以及截图)
- Android 三大图片缓存原理、特性对比