后台操作及IntentService

1.Service异步操作

2.IntentService

3.后台任务队列

4.进程保活

一.IntentService介绍

IntentService,可以看做是service和HandlerThread的结合体,在完成了使命之后会自动停止,适合需要在工作线程处理UI无关任务的场景。

IntentService是继承自Service并处理异步请求的一个类,在IntentService内有一个工作线程来处理耗时操作。

当任务执行完后,IntentService会自动停止,不需要我们去手动结束。

如果启动IntentService多次,那么每一个耗时操作会以工作队列的方式在IntentService的onHandleIntent回调方法中执行,依次执行,使用串行的方式,执行完自动结束。

二.IntentService的优点:不用开启线程

三.IntentService的缺点:使用广播向activity传值

四.使用IntentService网络请求json串,将json串使用广播发送给activity界面

思路:创建服务,注册服务

(1)创建服务:MyIntentService.java

public class MyIntentService extends IntentService {

public MyIntentService() {

super("MyIntentService");

}

@Override

public void onCreate() {

super.onCreate();

Log.i("----is","onCreate:");

}

@Override

protected void onHandleIntent(Intent intent) {

Bundle bundle=intent.getExtras();

String urlpath=bundle.getString("urlpath");

String sdpath=bundle.getString("sdpath");

try {

URL url=new URL(urlpath);

HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();

httpURLConnection.setRequestMethod("GET");

httpURLConnection.setConnectTimeout(2000);

httpURLConnection.setReadTimeout(2000);

httpURLConnection.connect();

if (httpURLConnection.getResponseCode()==200)

{

InputStream inputStream=httpURLConnection.getInputStream();

byte[] buffer=new byte[1024];

int len=0;

File file=new File(sdpath);

FileOutputStream fileOutputStream=new FileOutputStream(file);

int max=httpURLConnection.getContentLength();

int progress=0;

while ((len=inputStream.read(buffer))!=-1)

{

fileOutputStream.write(buffer,0,len);

progress+=len;

sendno(max,progress);

}

Intent intent1=new Intent();

intent1.setAction("com.bw.ok");

sendBroadcast(intent1);

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

Log.i("----sss","onHandleIntent:"+urlpath+sdpath);

}

(2)清单文件注册服务

<service

android:name=".MyIntentService"

android:exported="false" />

<service

(3)Activity代码

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

if (Build.VERSION.SDK_INT>Build.VERSION_CODES.M)

{

requestPermissions(new String[]{

Manifest.permission.WRITE_EXTERNAL_STORAGE,

Manifest.permission.READ_EXTERNAL_STORAGE

},101);

}

}

public void startfor(View view) {

Intent intent=new Intent(this,MyforgroundService.class);

startService(intent);

}

public void stopfor(View view) {

Intent intent=new Intent(this,MyforgroundService.class);

stopService(intent);

}

public void startis(View view) {

Intent intent=new Intent(this,MyIntentService.class);

Bundle bundle=new Bundle();

bundle.putString("urlpath","http://vfx.mtime.cn/Video/2019/03/18/mp4/190318214226685784.mp4");

bundle.putString("sdpath","/sdcard/Movies/dog.mp4");

intent.putExtras(bundle);

startService(intent);

}

}

作业:

1.前端:

<?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:orientation="vertical"

android:layout_height="match_parent"

tools:context=".MainActivity">

<Button

android:text="开启前台服务"

android:onClick="startfor"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

</Button>

<Button

android:text="停止前台服务"

android:onClick="stopfor"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

</Button>

<Button

android:text="开始intentser服务"

android:onClick="startis"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

</Button>

</LinearLayout>

item代码

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="horizontal"

android:layout_width="match_parent"

android:layout_height="match_parent">

<ProgressBar

android:id="@+id/pd"

style="@style/Widget.AppCompat.ProgressBar.Horizontal"

android:layout_width="match_parent"

android:layout_height="wrap_content">

</ProgressBar>

<ImageView

android:id="@+id/ivvv"

android:src="@mipmap/ic_launcher"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

</ImageView>

<LinearLayout

android:orientation="vertical"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

<TextView

android:id="@+id/title_tv"

android:text="歌词"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

</TextView>

<TextView

android:id="@+id/aa"

android:text="歌唱家"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

</TextView>

</LinearLayout>

</LinearLayout>

MyforgroundService里代码

public class MyforgroundService extends Service {

public MyforgroundService() {

}

@Override

public void onCreate() {

super.onCreate();

Log.i("----for","onCreate: ");

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

Log.i("----for","onStartCommand:");

NotificationManager notificationManager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);

RemoteViews remoteViews=new RemoteViews(getPackageName(),R.layout.item);

remoteViews.setTextViewText(R.id.title_tv,"你好阿廉");

remoteViews.setTextViewText(R.id.aa,"你好,老三");

remoteViews.setImageViewResource(R.id.ivvv,R.mipmap.ic_launcher_round);

Intent intent1=new Intent(this,MainActivity.class);

PendingIntent pendingIntent=PendingIntent.getActivity(this,101,intent1,PendingIntent.FLAG_UPDATE_CURRENT);

Notification.Builder builder=new Notification.Builder(MyforgroundService.this);

builder.setSmallIcon(R.mipmap.ic_launcher)

.setCustomContentView(remoteViews)

.setContentIntent(pendingIntent);

Notification notification=builder.build();

startForeground(1,notification);

return super.onStartCommand(intent, flags, startId);

}

@Override

public void onDestroy() {

Log.i("----for","onDestroy: ");

super.onDestroy();

}

@Override

public IBinder onBind(Intent intent) {

// TODO: Return the communication channel to the service.

throw new UnsupportedOperationException("Not yet implemented");

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值