Android使用StartService、BindService以及IntentService简单实现Toast

一、实现效果

点击不同的按钮,用不同的方式开启/关闭Service,在屏幕底部出现Toast

在这里插入图片描述

二、步骤

1、构造MyService.java、MyBindService.java、MyIntentService.java
2、改变MainActivity.java的布局
3、在MainActivity中实现相应按钮的点击响应
4、在AndroidManifest.xml中声明几个Service类

三、代码

1、构造MyService.java、MyBindService.java、MyIntentService.java

  • MyService.java
public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        Toast.makeText(this, "Start Service", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Stop Service", Toast.LENGTH_LONG).show();
    }
}
  • MyBindService.java
public class MyBindService extends Service
{
    public class MyBinder extends Binder
    {
        public MyBindService getService()
        {
            return MyBindService.this;
        }
    }

    MyBinder myBinder = new MyBinder();

    public void onCreate(){
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(this, "Bind Service", Toast.LENGTH_LONG).show();
        return myBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Toast.makeText(this, "Unbind Service", Toast.LENGTH_LONG).show();
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}

  • MyIntentService.java
public class MyIntentService extends IntentService {

    private Handler handler;

    public MyIntentService()
    {
        super("MyIntentService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        handler = new Handler();
    }

    protected void onHandleIntent(Intent intent)
    {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), "Intent Service", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

2、改变MainActivity.java的布局

  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_marginTop="100dp"
    tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center_horizontal">
        <Button
            android:id="@+id/start_service"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginVertical="10dp"
            android:textAllCaps="false"
            android:text="StartService"/>
        <Button
            android:id="@+id/stop_service"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginVertical="10dp"
            android:textAllCaps="false"
            android:text="StopService"/>
        <Button
            android:id="@+id/bind_service"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginVertical="10dp"
            android:textAllCaps="false"
            android:text="BindService"/>
        <Button
            android:id="@+id/unbind_service"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginVertical="10dp"
            android:textAllCaps="false"
            android:text="UnbindService"/>
        <Button
            android:id="@+id/intent_service"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginVertical="10dp"
            android:textAllCaps="false"
            android:text="IntentService"/>
    </LinearLayout>
</LinearLayout>

3、在MainActivity中实现相应按钮的点击响应

  • MainActivity.java
public class MainActivity extends AppCompatActivity {

    private boolean isBind = false;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            isBind=true;
            MyBindService.MyBinder myBinder = (MyBindService.MyBinder)service;
            MyBindService myBindService = myBinder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBind = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button start_service = (Button) findViewById(R.id.start_service);
        Button stop_service = (Button) findViewById(R.id.stop_service);
        Button bind_service = (Button) findViewById(R.id.bind_service);
        Button unbind_service = (Button) findViewById(R.id.unbind_service);
        Button intent_service = (Button) findViewById(R.id.intent_service);

        start_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,MyService.class);
                startService(intent);
            }
        });

        stop_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,MyService.class);
                stopService(intent);
            }
        });

        bind_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,MyBindService.class);
                bindService(intent,connection,BIND_AUTO_CREATE);
            }
        });

        unbind_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isBind)
                {
                    unbindService(connection);
                }
            }
        });

        intent_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,MyIntentService.class);
                startService(intent);
            }
        });
    }
}

4、在AndroidManifest.xml中声明几个Service类

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.practice6">

    <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=".MyService"></service>
        <service android:name=".MyBindService"></service>
        <service android:name=".MyIntentService"></service>
    </application>

</manifest>

如果对你有帮助的话,欢迎点赞和收藏~

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很抱歉,作为语言模型AI,我没有权限进行编程操作,但我可以提供一些思路和代码示例供您参考。 对于第2个问题,您可以在MainActivity的onCreate方法中通过Intent启动一个Service,并在Service使用Broadcast机制进行数据传递,实现简单的倒计时定时器: MainActivity.java ```java public class MainActivity extends AppCompatActivity { private TextView mTextView; private Button mStartButton; private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int count = intent.getIntExtra("count", 0); mTextView.setText(String.valueOf(count)); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = findViewById(R.id.text_view); mStartButton = findViewById(R.id.start_button); mStartButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, CountdownService.class); startService(intent); } }); } @Override protected void onStart() { super.onStart(); IntentFilter filter = new IntentFilter(); filter.addAction("com.example.countdown"); registerReceiver(mReceiver, filter); } @Override protected void onStop() { super.onStop(); unregisterReceiver(mReceiver); } } ``` CountdownService.java ```java public class CountdownService extends Service { private int mCount; private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Intent broadcastIntent = new Intent(); broadcastIntent.setAction("com.example.countdown"); broadcastIntent.putExtra("count", mCount); sendBroadcast(broadcastIntent); mCount--; } }; private Handler mHandler = new Handler(); private Runnable mRunnable = new Runnable() { @Override public void run() { mHandler.postDelayed(this, 1000); Intent intent = new Intent(); intent.setAction("com.example.countdown"); intent.putExtra("count", mCount); sendBroadcast(intent); mCount--; } }; @Override public void onCreate() { super.onCreate(); mCount = 10; mHandler.postDelayed(mRunnable, 1000); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Intent broadcastIntent = new Intent(); broadcastIntent.setAction("com.example.countdown"); broadcastIntent.putExtra("count", mCount); sendBroadcast(broadcastIntent); return START_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { super.onDestroy(); mHandler.removeCallbacks(mRunnable); } } ``` activity_main.xml ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" ...> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="24sp" android:text="10" android:layout_centerInParent="true"/> <Button android:id="@+id/start_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start" android:layout_below="@id/text_view" android:layout_centerHorizontal="true"/> </RelativeLayout> ``` 对于第3个问题,您可以通过绑定Service的方式启动一个Service,并在Activity中通过IBinder获取Service实例,从而调用Service中的方法实现简单的倒计时定时器: MainActivity.java ```java public class MainActivity extends AppCompatActivity { private TextView mTextView; private Button mStartButton; private CountdownService mCountdownService; private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mCountdownService = ((CountdownService.CountdownBinder) service).getService(); mCountdownService.setCallback(new CountdownService.Callback() { @Override public void onCountdown(int count) { mTextView.setText(String.valueOf(count)); } }); } @Override public void onServiceDisconnected(ComponentName name) { mCountdownService = null; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = findViewById(R.id.text_view); mStartButton = findViewById(R.id.start_button); mStartButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, CountdownService.class); bindService(intent, mServiceConnection, BIND_AUTO_CREATE); } }); } @Override protected void onDestroy() { super.onDestroy(); unbindService(mServiceConnection); } } ``` CountdownService.java ```java public class CountdownService extends Service { private int mCount; private Callback mCallback; public interface Callback { void onCountdown(int count); } public class CountdownBinder extends Binder { CountdownService getService() { return CountdownService.this; } } private final IBinder mBinder = new CountdownBinder(); private Handler mHandler = new Handler(); private Runnable mRunnable = new Runnable() { @Override public void run() { mHandler.postDelayed(this, 1000); mCallback.onCountdown(mCount); mCount--; } }; @Override public void onCreate() { super.onCreate(); mCount = 10; mHandler.postDelayed(mRunnable, 1000); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public void onDestroy() { super.onDestroy(); mHandler.removeCallbacks(mRunnable); } public void setCallback(Callback callback) { mCallback = callback; } } ``` activity_main.xml ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" ...> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="24sp" android:text="10" android:layout_centerInParent="true"/> <Button android:id="@+id/start_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start" android:layout_below="@id/text_view" android:layout_centerHorizontal="true"/> </RelativeLayout> ``` 希望这些代码示例能够对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值