1.Service异步操作
3.后台任务队列
4.进程保活
一.IntentService介绍
IntentService,可以看做是service和HandlerThread的结合体,在完成了使命之后会自动停止,适合需要在工作线程处理UI无关任务的场景。
android为我们提供了一个IntentService,来替我们默认创建一个子线程,同时在线程执行完毕以后,主动结束service
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);
}
public void sendno(int max,int progress)
{
NotificationManager notificationManager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
RemoteViews remoteViews=new RemoteViews(getPackageName(),R.layout.item);
remoteViews.setProgressBar(R.id.pd,max,progress,false);
Notification.Builder builder=new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setCustomContentView(remoteViews);
Notification notification=builder.build();
notificationManager.notify(1,notification);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("----is","onDestroy:");
}
}
(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);
}
public void HttpGet(View view) {
new MyAsyncTask().execute("http://43.143.146.165:7777/foods/getFoods?pageSize=10¤tPage=1");
}
public void HttpPost(View view) {
new MyAsyncTaskPost().execute("http://43.143.146.165:7777/foods/postFoods");
}
public class MyAsyncTaskPost extends AsyncTask<String,Void,String>
{
@Override
protected String doInBackground(String... strings) {
String path = strings[0];
HashMap<String,Integer> stringIntegerHashMap = new HashMap<>();
stringIntegerHashMap.put("currentPage",1);
stringIntegerHashMap.put("pageSize",10);
HttpManager.getInstance().postString(path,stringIntegerHashMap);
return null;
}
}
public class MyAsyncTask extends AsyncTask<String,Void,String>
{
@Override
protected String doInBackground(String... strings) {
String path=strings[0];
String json=HttpManager.getInstance().getString(path);
return json;
}
}
}
//饿汉式,//懒汉式,//双重锁
//饿汉式
private HttpManager() {
}
public static HttpManager httpManager=new HttpManager();
public static HttpManager getInstance()
{
return httpManager;
}
//懒汉式
private HttpManager() {
}
private static HttpManager httpManager=null;
public static HttpManager getInstance()
{
if (httpManager==null)
{
httpManager=new HttpManager();
}
return httpManager;
}
//双重锁
private HttpManager() {
}
private static volatile HttpManager httpManager=null;
public static HttpManager getInstance()
{
if (httpManager==null)
{
synchronized(HttpManager.class)
{
if (httpManager==null)
{
httpManager=new HttpManager();
}
};
}
return httpManager;
}
GET和POST的方法
public String getString(String path)
{
try {
URL url=new URL(path);
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(2000);
httpURLConnection.setConnectTimeout(2000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode()==200)
{
InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String str="";
StringBuilder stringBuilder=new StringBuilder();
while ((str=bufferedReader.readLine())!=null)
{
stringBuilder.append(str);
}
String json=stringBuilder.toString();
Log.i("--json","getString: "+json);
return json;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//
public String postString(String path, HashMap<String,Integer>hashMap)
{
try {
URL url=new URL(path);
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setReadTimeout(2000);
httpURLConnection.setConnectTimeout(2000);
httpURLConnection.connect();
boolean isfirst=true;
String body="";
Set<Map.Entry<String,Integer>>entries=hashMap.entrySet();
for (Map.Entry<String,Integer> entry:entries)
{
String key=entry.getKey();
Integer vaule=entry.getValue();
if (isfirst)
{
isfirst=false;
}else{
body+="&";
}
body+= URLEncoder.encode(key,"UTF-8")+"="+vaule;
}
Log.i("---body","postString: "+body);
OutputStream outputStream=httpURLConnection.getOutputStream();
outputStream.write(body.getBytes());
outputStream.flush();
if (httpURLConnection.getResponseCode()==200)
{
InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String str="";
StringBuilder stringBuilder=new StringBuilder();
while ((str=bufferedReader.readLine())!=null)
{
stringBuilder.append(str);
}
String json=stringBuilder.toString();
Log.i("---json","postString: "+json);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}