一个标准的service使用方法 附带notification用法

main_activity

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;

import android.graphics.Color;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

import android.widget.RemoteViews;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "godv";
    private static final String ACTION = "godv";
    private static final int NOTIFICATION_ID = 9001;
    private MsgService mSgService;
    private ServiceConnection mConn;
    private NotificationManager mManage;
    private int mMark = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button mStarButton = findViewById(R.id.startTip);
        Button mEndButton = findViewById(R.id.endTip);
        connectService();
        mStarButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSgService.startTip();
            }
        });
        mEndButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSgService.endTip();
            }
        });
        registerReceiver();
    }

    private void registerReceiver() {
        BroadcastReceiver mReceiver = new NotificationBroadcast();
        IntentFilter filter = new IntentFilter(ACTION);
        registerReceiver(mReceiver, filter);
    }

    private void setListener() {
        mSgService.setOnProgressListener(new OnProgressListener() {
            @Override
            public void onProgress(final int count) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showNotification(count + "");
                        if (count % mMark == 0) {
                            Toast.makeText(MainActivity.this, "godv", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    private void connectService() {
        final ProgressDialog dialog = ProgressDialog.show(this, getResources().getString(R.string.tip),
                getResources().getString(R.string.loading));
        new Thread(new Runnable() {
            @Override
            public void run() {
                mConn = new ServiceConnection() {
                    @Override
                    public void onServiceDisconnected(ComponentName name) {
                    }

                    @Override
                    public void onServiceConnected(ComponentName name, IBinder service) {
                        mSgService = ((MsgService.MsgBinder) service).getService();
                        dialog.dismiss();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, getResources().getString(R.string.success)
                                        , Toast.LENGTH_SHORT).show();
                            }
                        });
                        setListener();
                    }
                };
                Intent intent = new Intent(MainActivity.this, MsgService.class);
                bindService(intent, mConn, Context.BIND_AUTO_CREATE);
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mConn);
    }

    public interface OnProgressListener {
        void onProgress(int count);
    }

    private void showNotification(String context) {
        String channelID = "channelID";
        CharSequence channelName = "channelName";
        mManage = (NotificationManager) getBaseContext().getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
            channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),
                    Notification.AUDIO_ATTRIBUTES_DEFAULT);
            channel.enableLights(true);
            channel.setLightColor(Color.RED);
            mManage.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext(), channelID);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        RemoteViews contentView = new RemoteViews(getBaseContext().getPackageName(), R.layout.notifa);
        contentView.setTextViewText(R.id.notification_tv, context);
        int requestCode = 1;
        PendingIntent homeIntent = PendingIntent.getBroadcast(this, requestCode, new Intent(ACTION),
                PendingIntent.FLAG_UPDATE_CURRENT);
        contentView.setOnClickPendingIntent(R.id.notification_btn, homeIntent);
        builder.setCustomContentView(contentView);
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        mManage.notify(NOTIFICATION_ID, notification);
    }

    public class NotificationBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            mManage.cancel(NOTIFICATION_ID);
            mSgService.endTip();
        }
    }
}

service

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

/**
 * Implemented sevice class
 */
public class MsgService extends Service {
    //Intervals
    private static final int INTERVAL = 1000;
    //Simulate lazy loading
    private static final int DELAY = 3000;
    private static boolean sBoot = true;
    private MainActivity.OnProgressListener mProgressListener;
    private int mCount = 0;
    private int mInit = 0;

    public void setOnProgressListener(MainActivity.OnProgressListener onProgressListener) {
        this.mProgressListener = onProgressListener;
    }

    public void startTip() {
        sBoot = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (sBoot) {
                    mCount++;
                    Log.i(MainActivity.TAG, "mCount:" + mCount);
                    mProgressListener.onProgress(mCount);
                    SystemClock.sleep(INTERVAL);
                }
            }
        }).start();
    }

    public void endTip() {
        sBoot = false;
        mCount = mInit;
    }

    @Override
    public IBinder onBind(Intent intent) {
        SystemClock.sleep(DELAY);
        return new MsgBinder();
    }

    public class MsgBinder extends Binder {
        public MsgService getService() {
            return MsgService.this;
        }
    }
}

配置service

<service android:name="com.example.service_count.MsgService" />

Strings

<resources>
    <string name="app_name">Service_Count</string>
    <string name="start">开始</string>
    <string name="stop">停止</string>
    <string name="loading">等待连接</string>
    <string name="tip">提示</string>
    <string name="success">连接成功</string>
    <string name="exit">退出</string>
</resources>

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值