摘要:本文将带你了解Android基础之Sevice组件的简单使用,希望本文对大家学Android有所帮助。
1、本例实现了简单的Service(服务)的创建、启动和停止,点击“启动SERVICE”页面会显示“服务被创建”,接着是“服务被启动”。点击“停止SERVICE”页面提示“服务被停止”。
2、基本代码
ServiceDemo: package thonlon.example.cn.servicedemo; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Toast; /** * 绑定服务的时候被调用 */ public class ServiceDemo extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } /** * Service被创建后被调用 */ @Override public void onCreate() { Toast.makeText(ServiceDemo.this,"服务被创建",Toast.LENGTH_SHORT).show(); Log.d("onCreate", "服务被创建"); } /** * Service被开始后调用 * * @param intent * @param flags * @param startId * @return */ @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(ServiceDemo.this,"服务被启动",Toast.LENGTH_SHORT).show(); Log.d("onStartCommand", "服务被启动"); return super.onStartCommand(intent, flags, startId); } /** * Service被停止后调用 */ @Override public void onDestroy() { Toast.makeText(ServiceDemo.this,"服务被停止",Toast.LENGTH_SHORT).show(); Log.d("onDestroy", "服务被停止"); } } MainActivity: package thonlon.example.cn.servicedemo; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onClick(View v){ Intent intent = new Intent(); intent.setClass(this,ServiceDemo.class); switch (v.getId()){ case R.id.btn_start_service://第一次点启动Service,服务会被创建,之后再点击启动服务不会再被创建,服务已经被创建 startService(intent); break; case R.id.btn_stop_service: stopService(intent); break; } }
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号