学习日志10

1.学习目标
显示服务
隐式服务
停止服务
广播接收者
2.创建一个新的类使用线程

package com.example.myapplication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class CustomService extends Service {

    private final String TAG = "start_stop_service";//标记
    private Thread thread;//线程
    private boolean isRunning;//线程循环控制变量

    @Override
    public void onCreate(){
        super.onCreate();
        Log.d(TAG,"CustomService.onCreate() invoked.");
    }

    @Override
    public int onStartCommand(Intent intent,int flags , final int startId){
        Log.d(TAG,"CustomService.onStartCommand() invoked.");
        //设置线程循环控制变量为真
        isRunning = true;
        //判断意图是否为空
        if (intent != null){
            //创建线程
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while(isRunning){
                        Log.d(TAG,"服务正在进行中·····startId:" + startId + ", hashCode" + CustomService.this.hashCode());
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            //启动线程
            thread.start();
        }
        return Service.START_NOT_STICKY;
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.d(TAG,"CustomService.onDestroy() invoked.");
        isRunning = false;
        thread = null;//销毁线程
        stopSelf();//停止服务
    }
}



再去创建三个按钮分别为显示,隐式显示,停止。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="@string/explicitly_start_service"
        android:onClick="doExplicitlyStartService"
        android:textSize="20sp"
        android:id="@+id/btnExplicitlyStartService"/>

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:id="@+id/btnImplicitlyStartService"
        android:text="@string/implicitly_start_service"
        android:onClick="doImplicitlyStartService"
        android:textSize="20sp"/>

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="@string/stop_service"
        android:onClick="doStopService"
        android:textSize="20sp"
        android:id="@+id/btnStopService"/>

</LinearLayout>

去主窗口使用意图创建启动服务

package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /**
     * 显示启动服务
     * @param view
     */
    public void doExplicitlyStartService(View view){
        //创建启动指定服务的意图
        Intent intent = new Intent(this,CustomService.class);
        //按照意图启动指定服务
        startService(intent);
    }

    /**
     * 隐式启动服务
     *
     * @param view
     */
    public void doImplicitlyStartService(View view){
        //创建意图
        Intent intent = new Intent();
        //设置意图动作
        intent.setAction("custom_service");
        //设置意图包名
        intent.setPackage(getPackageName());
        //按照意图启动服务
        startService(intent);

    }

    /**
     * 停止服务
     *
     * @param view
     */
    public void doStopService(View view){
        //创建启动指定服务的意图
        Intent intent = new Intent(this,CustomService.class);
        //按意图停止服务
        stopService(intent);
    }

}

去清单文件 AndroidManifest.xml注册一个customservice文件,定义一个意图过滤器来接收(监听)指定的action

  <service android:name=".CustomService">
            <intent-filter>
                <action android:name="custom_service" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </service>

运行
在这里插入图片描述
分别点击三个按钮
在这里插入图片描述
3.简介广播接收者
广播接收者可以分为:
1.标准广播
标准广播( Normal Broadcasts) 是一种完全异步执行的广播,在广播发出之后,所有的广播接收者几乎都会在同一时刻接收到这条广播消息,因此它们之间没有任何先后顺序可言。这种广播的效率会比较高,但同时也意味着它是无法被截断的。标准广播也叫无序广播,无序广播不能设置优先级,没有abortBroadcast()方法。
2.有序广播
有序广播( Ordered Broadcasts) 则是一种同步执行的广播,在广播发出之后,同一时刻只会有一个广播接收者能够收到这条广播消息,当这个广播接收者中的逻辑执行完毕后,广播才会继续传递。所以此时的广播接收者是有先后顺序的,优先级高的广播接收者就可以先 收到广播消息,并且前面的广播接收者还可以截断正在传递的广播,这样后面的广播接收者就无法收到广播消息了。有序广播可以设置优先级, 有 abortBroadcast() 方法。
4.使用广播接收者
1.创建一个类,继承BroadcastReceiver,并重写父类的 onReceive()方法。

package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class CustomReceiver extends BroadcastReceiver {
    private final String TAG = "send_receive_broadcast";//标记
    private final String TNTENT_ACTION_SEND_MESSAGE = "net.nell.intent.action.SEND_MESSAGE";

    @Override
    public void onReceive(Context context, Intent intent) {
        //按照频道获取广播信息
        if (intent.getAction().equals(TNTENT_ACTION_SEND_MESSAGE)){
            //获取广播信息
            String message = intent.getStringExtra("message");
            //输出广播信息
            Log.d(TAG,message);
        }

    }
}


2.创建对话框和按钮

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="20dp"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edtMessage"
        android:hint="@string/input_message"
        android:singleLine="true"
        android:textSize="20sp"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnSendBroadcast"
        android:onClick="doSendBroadcast"
        android:text="@string/send_broadcast"
        android:textSize="20sp"/>

</LinearLayout>

3.在主窗口写入向其他应用中注册的广播接收者发送广播

package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private final String TAG = "send_receive_broadcast";//标记
    private final String INTENT_ACTION_SEND_MESSAGE = "net.nell.intent.action.SEND_MESSAGE";
    private EditText edtMessage;//消息编辑框
    private int broadcastCount;//发送广播次数


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edtMessage = findViewById(R.id.edtMessage);
    }
    /**
     * 发送广播
     *
     * @param view
     */
    public void doSendBroadcast(View view){
        //统计发送广播次数
        broadcastCount++;
        //获取用户输入到广播的信息
        String message = edtMessage.getText().toString();
        //创建意图
        Intent intent = new Intent();
        //设置意图动作
        intent.setAction(INTENT_ACTION_SEND_MESSAGE);
        //设置意图携带的附加内容
        intent.putExtra("message","第"+broadcastCount+"次广播信息:"+message);
        //按照意图发送广播
        sendBroadcast(intent);

    }
}

在这里插入图片描述
在这里插入图片描述
今天的学习到此为止了,明天开始弹窗的学习。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值