플래시 페이지 관련 처리 에 대해 자세히 이야기 하 다.

22591 단어 플래시 스크린
기능 모듈 에 따라 구분(Android 개발 추천 이 방법)
    - Activity   mobilesafe.activty
    - 백 스테이지 서비스   mobilesafe.service
    - 방송 수신 자 mobilesafe.receiver
    - 데이터베이스 mobilesafe.db.dao
    - 대상(java bean)mobilesafe.domain/bean
    - 사용자 정의 컨트롤 mobilesafe.view
    - 도구 류 mobilesafe.utils
    - 비 즈 니스 논리 mobilesafe.engine
플래시 페이지(Splash)기능:
-로고 전시,회사 브랜드
-프로젝트 초기 화
-검 측 버 전 업데이트
-검사 프로그램의 합 법성(예:네트워크 여 부 를 판단 하고 있 으 면 실행)
AndroidMinifest.xml      4 대 구성 요 소 를 모두 여기에 설정 해 야 합 니 다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.mxn.mobilesafe"
 android:versionCode="1" //   
 android:versionName="1.0" > //   
 <uses-sdk
  android:minSdkVersion="16"
  android:targetSdkVersion="21" />
//       
 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_PHONE_STATE" />
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
 <uses-permission android:name="android.permission.READ_CONTACTS" />
 <uses-permission android:name="android.permission.SEND_SMS" />
 <uses-permission android:name="android.permission.RECEIVE_SMS" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
 <uses-permission android:name="android.permission.VIBRATE" />
 <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
 <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
 <uses-permission android:name="android.permission.GET_PACKAGE_SIZE"/>
 <uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>
 <application
  android:allowBackup="true"
  android:icon="@drawable/ic_launcher"
  android:label="@string/app_name"
  android:theme="@style/AppTheme" > //  
   //activity   
  <activity
android:name="com.mxn.mobilesafe.activity.SplashActivity"
   android:label="@string/app_name" >
   <intent-filter> //   activity
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.HomeActivity" />
  <activity android:name="com.mxn.mobilesafe.activity.SettingActivity" />
  <activity android:name="com.mxn.mobilesafe.activity.LostFindActivity" >
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.Setup1Activity" >
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.Setup2Activity" >
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.Setup3Activity" >
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.Setup4Activity" >
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.ContactActivity" >
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.AtoolsActivity" >
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.AddressActivity" >
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.CallSafeActivity" >
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.AppManagerActivity" >
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.TaskManagerActivity">   
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.TaskManagerSettingActivity">   
  </activity>
  <activity android:name="com.mxn.mobilesafe.activity.AntivirusActivity"></activity>
  <activity android:name="com.mxn.mobilesafe.activity.AppLockActivity"></activity>
  <activity android:name="com.mxn.mobilesafe.activity.CleanCacheActivity"></activity>
//         
  <receiver android:name=".receiver.BootCompleteReceiver" >
   <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
   </intent-filter>
  </receiver>
  <receiver android:name=".receiver.SmsReceiver" >
   <intent-filter android:priority="2147483647" >
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
   </intent-filter>
  </receiver>
  <!--
  <receiver android:name=".receiver.OutCallReceiver" >       
   <intent-filter>
    <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
   </intent-filter>
  </receiver>
  -->
//     
  <service android:name="com.mxn.mobilesafe.service.LocationService" >
  </service>
  <service android:name="com.mxn.mobilesafe.service.AddressService" >
  </service>
  <service android:name="com.mxn.mobilesafe.service.KillProcessService"></service>
  <service android:name="com.mxn.mobilesafe.service.WatchDogService"></service>
 </application>
</manifest>
activity_splash.xml

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.mxn.mobilesafe.SplashActivity"
 android:background="@drawable/launcher_bg" 
 android:id="@+id/rl_root">
 <TextView
  android:id="@+id/tv_version"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignParentBottom="true"
  android:layout_centerHorizontal="true"
  android:layout_marginBottom="202dp"
  android:textSize="22sp"
  android:textColor="#000"
  android:shadowColor="#f00" //        
  android:shadowDx="1"
  android:shadowDy="1"
  android:shadowRadius="1"
  android:text="   :1.0" />
 <ProgressBar
  android:id="@+id/progressBar1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignTop="@+id/tv_version"
  android:layout_centerHorizontal="true"
  android:layout_marginTop="54dp" />
 <TextView
  android:id="@+id/tv_progress"
  android:visibility="gone"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignParentBottom="true"
  android:layout_alignParentLeft="true"
  android:textColor="#f00"
  android:textSize="16sp"
  android:text="    " />
</RelativeLayout>
SplashActivity.java

public class SplashActivity extends Activity {
 protected static final int CODE_UPDATE_DIALOG;
 protected static final int CODE_URL_ERROR;
 protected static final int CODE_NET_ERROR;
 protected static final int CODE_JSON_ERROR;
 protected static final int CODE_ENTER_HOME;
 private TextView tvVersion;
 private TextView tvProgress;//       
 //         
 private String mversionName;//    
 private int mversionCode;//    
 private String mDesc;//     
 private String mdowmloadurl;//     
 private Handler mHandler = new Handler() {
  public void handleMessage(android.os.Message msg) {
   switch (msg.what) {
   case CODE_UPDATE_DIALOG:
    showUpdateDialog();//       
    break;
   case CODE_URL_ERROR:
    Toast.makeText(SplashActivity.this, "url  ", Toast.LENGTH_SHORT).show();
    enterHome();
    break;
   case CODE_NET_ERROR:
    Toast.makeText(SplashActivity.this, "    ", Toast.LENGTH_SHORT).show();
    enterHome();
    break;
   case CODE_JSON_ERROR:
    Toast.makeText(SplashActivity.this, "json        ", Toast.LENGTH_SHORT).show();
    enterHome();
    break;
   case CODE_ENTER_HOME:
    enterHome();
    break;
   default:
    break;
   }
  };
 };
 private SharedPreferences sp;
 private RelativeLayout rlRoot;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_splash);
  tvVersion = (TextView) findViewById(R.id.tv_version);
  tvProgress = (TextView) findViewById(R.id.tv_progress);//     
  tvVersion.setText("   :" + getVersionCode());//        ,      
  rlRoot = (RelativeLayout) findViewById(R.id.rl_root);
  //          
  sp = getSharedPreferences("config", MODE_PRIVATE);
  boolean autoUpdate = sp.getBoolean("auto_update", true);
  copyDB("address.db");//          
  copyDB("antivirus.db");//     
  //     
  updateVirus();
  if(autoUpdate){
   checkVersion();
  }else{
   mHandler.sendEmptyMessageDelayed(CODE_ENTER_HOME, 2000);
  }
  //         
  AlphaAnimation anim = new AlphaAnimation(0.3f, 1f);
  anim.setDuration(2000);
  rlRoot.startAnimation(anim);
 }
 //       
 private void updateVirus() {
  //              MD5    
  HttpUtils httputils = new HttpUtils();
  String url = "http://172.28.3.112:8080/virus.json";
  httputils.send(HttpMethod.GET, url, new RequestCallBack<String>(){
   @Override
   public void onFailure(HttpException arg0, String arg1) {
    // TODO Auto-generated method stub
   }
   @Override
   public void onSuccess(ResponseInfo<String> arg0) {
    // TODO Auto-generated method stub
    //System.out.println(arg0.result);
//    JSONObject jsonobject = new JSONObject(arg0.result);
//    String md5 = jsonobject.getString("md5");
//    String desc = jsonobject.getString("desc");
   }
  });
 }
 //        
 private int getVersionCode() {
  PackageManager packgeManager = getPackageManager();//       。。    ,        apk   (      )
  try {//       。。 getPackageName()             package="com.mxn.mobilesafe"
   PackageInfo packageInfo = packgeManager.getPackageInfo(getPackageName(), 0);
   int versionCode = packageInfo.versionCode;
   String versionName = packageInfo.versionName;
   System.out.println("versionname=" + versionName + ";" + "versioncode=" + versionCode);
   return versionCode;
  } catch (NameNotFoundException e) {
   //        
   e.printStackTrace();
  }
  return -1;
 }
 //               
 private void checkVersion() {
  final long startTime = System.currentTimeMillis();
  new Thread() {//               
   public void run() {
    Message msg = Message.obtain();
    HttpURLConnection con = null;
    try {//     :localhost              : 10.0.0.2   
     URL url = new URL("http://10.0.2.2:8080/update.json");
     //     
     con = (HttpURLConnection) url.openConnection();
     con.setRequestMethod("GET");//      
     con.setConnectTimeout(5000);//       ,5S
     con.setReadTimeout(5000);//       ,    ,          
     con.connect();//      
     int responseCode = con.getResponseCode();//     
     if (responseCode == 200) {
      //      
      InputStream inputStream = con.getInputStream();
      //        
      String result = StreamUtils.readFormStream(inputStream);//     StreamUtils   
      System.out.println("      :" + result);
       //result   json   ,    
      //   json
      JSONObject jo = new JSONObject(result);
      mversionName = jo.getString("versionName");//          
      mversionCode = jo.getInt("versionCode");//          
      mDesc = jo.getString("description");//           
      mdowmloadurl = jo.getString("downloadUrl");//           
      System.out.println(mDesc);
      System.out.println(mversionCode);
      //           ,       ,             ,       
      if (mversionCode > getVersionCode()) {
       System.out.println("    ,     ");
       msg.what = CODE_UPDATE_DIALOG;
       // showUpdateDialog();//           ,android          ,              handler.
      } else {//         
       msg.what = CODE_ENTER_HOME;
      }
     }
    } catch (MalformedURLException e) {// url     
     msg.what = CODE_URL_ERROR;
     e.printStackTrace();
    } catch (IOException e) {//      
     //           msg.obj =
     msg.what = CODE_NET_ERROR;// what      ,      !
     e.printStackTrace();
    } catch (JSONException e) {// json    
     msg.what = CODE_JSON_ERROR;
     e.printStackTrace();
    } finally {
     long endTime = System.currentTimeMillis();
     long timeUsed = endTime - startTime;//          
     if (timeUsed < 2000) {
      try {//     2s,      2S
       Thread.sleep(2000 - timeUsed);
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
     }
     mHandler.sendMessage(msg);//       , handlemessage        
     if (con != null) {
      con.disconnect();
     }
    }
   }
  }.start();
 }
  //     
 private void showUpdateDialog() {
  System.out.println("       ");
  //      
  AlertDialog.Builder builder = new AlertDialog.Builder(this);//context  
  builder.setTitle("    " + mversionName);
  builder.setMessage(mDesc);
  // builder.setCancelable(false);//         ,      
  builder.setPositiveButton("    ", new OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    System.out.println("    ");
    // download  
    download();
   }
  });
  builder.setNegativeButton("    ", new OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
    enterHome();
   }
  });
  builder.setOnCancelListener(new OnCancelListener() {
   //       ,          
   @Override
   public void onCancel(DialogInterface dialog) {
    enterHome();
   }
  });
  builder.show();
 }
 protected void download() {//        apk  
  if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    //      sd ,sd         
   tvProgress.setVisibility(View.VISIBLE);//     
   String target = Environment.getExternalStorageDirectory() + "/update.apk";//           ,sd     
   // xutils  ,  HttpUtils      ,    jar 
   HttpUtils utils = new HttpUtils();
   utils.download(mdowmloadurl, target, new RequestCallBack<File>() {
    @Override //       
    public void onLoading(long total, long current, boolean isUploading) {
     // TODO Auto-generated method stub
     super.onLoading(total, current, isUploading);
     System.out.println("    :" + current + "/" + total);
     tvProgress.setText("    :" + current * 100 / total + "%");
    }
    @Override
    public void onSuccess(ResponseInfo<File> arg0) {
     // TODO Auto-generated method stub
     Toast.makeText(SplashActivity.this, "    ", Toast.LENGTH_SHORT).show();
     //       ,         。。Intent.ACTION_VIEW  xml action   
     Intent intent = new Intent(Intent.ACTION_VIEW);//       
     intent.addCategory(Intent.CATEGORY_DEFAULT);
      intent.setDataAndType(Uri.fromFile(arg0.result),
      "application/vnd.android.package-archive");
     // startActivity(intent);
     startActivityForResult(intent, 0);//         ,     ,    onActivityResult,    
    }
    @Override
    public void onFailure(HttpException arg0, String arg1) {
     // TODO Auto-generated method stub
     Toast.makeText(SplashActivity.this, "    ", Toast.LENGTH_SHORT).show();
    }
   });
  } else {
   Toast.makeText(SplashActivity.this, "  SD ", Toast.LENGTH_SHORT).show();
  }
 } 
 @Override//      ,     
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  System.out.println("      ,       。");
  enterHome();
  super.onActivityResult(requestCode, resultCode, data);
 }
 private void enterHome() {//      
  Intent intent = new Intent(this, HomeActivity.class);
  startActivity(intent);
  finish();
 }
 //     , assets      data/data/com.mxn.mobilesafe/files   
 private void copyDB(String dbName){
  //      
  File destFile = new File(getFilesDir(),dbName);
  if(destFile.exists()){
   System.out.println("   ");
  }
  FileOutputStream out = null;
  InputStream in = null;
  try {
   in = getAssets().open(dbName);
   out = new FileOutputStream(destFile);
   int len = 0; 
   byte[] buffer = new byte[1024];
   while((len = in.read(buffer))!=-1){
    out.write(buffer,0,len);
   } 
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   try {
    in.close();
    out.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}
StreamUtils.java

 /*
 *       
 *             
 */
public class StreamUtils {
 //       String   
 public static String readFormStream(InputStream in) throws IOException{
   //             
  ByteArrayOutputStream out = new ByteArrayOutputStream();
   //         
  int len = 0 ;
  //         
  byte[] buffer = new byte[1024];
   //               ,         
  while((len=in.read(buffer))!=-1){
    //                      
   out.write(buffer,0,len);   
  }
  String result = out.toString();
   //     
  in.close();
  out.close();
  return result;
//   //                      
//   byte data[] = out.toByteArray(); 
//  //                (                       ,android      UTF-8) 
//   return new String(data, "UTF-8"); 
 }
}
시스템 설치 인터페이스의 activity 설정:

<activity android:name=".PackageInstallerActivity"
android:configChanges="orientation|keyboardHidden"
android:theme="@style/Theme.Transparent">
   <intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:scheme="content" />
    <data android:scheme="file" />
    <data android:mimeType="application/vnd.android.package-archive" />
   </intent-filter>
  </activity>
저희 서버 는 tomcat 를 사용 하고 있 습 니 다.안에 설치 되 어 있 습 니 다.  새 버 전의 apk 와 update.json:

코드 를 apk 파일 로 압축 하기:

관련 된 지식 포인트:
PackageManager  패키지 관리자,핸드폰 에 있 는 모든 apk 정보(목록 파일 정보)가 져 오기
버 전 업데이트 절차:

네트워크 요청
>  * URL
>  * HttpUrlConntetion
JSON 해석
> * JSONObject  제 이 슨
> * JSONArray
대화 상자 팝 업
> AlertDialog
> AlertDialog.Builder
하위 스 레 드 업데이트 UI
> * Handler + message
> * runOnUiThread(runnable)
페이지 간 점프 Intent
GitHub 는 xUtils 프레임 워 크 를 다운로드 하고 다운로드 한 jar 패 키 지 를 프로젝트 에 가 져 옵 니 다
AlertDialog.Builder(this)
자 류 는 부류 의 모든 방법 을 가지 고 있 으 며,더 많은 방법 을 가 질 수 있다.부 류 는 자 류 를 가 질 수 없 는 방법 이다.
Activity(token),Context(token 없 음)
평소 context 대상 을 가 져 오 려 면 Activity 를 우선 선택 하고 버그 가 발생 하지 않도록 getApplication Context()를 사용 하지 않 습 니 다.
activity 는 context 의 하위 클래스 입 니 다.
이상 은 본 고의 모든 내용 입 니 다.본 고의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 도움 이 되 기 를 바 랍 니 다.또한 저 희 를 많이 지지 해 주시 기 바 랍 니 다!

좋은 웹페이지 즐겨찾기