提交 95c17c32 创建 作者: 宋海霞's avatar 宋海霞

init

上级
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<codeStyleSettings language="XML">
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
<arrangement>
<rules>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:android</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:id</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>style</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
<order>ANDROID_ATTRIBUTE_ORDER</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>.*</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
</rules>
</arrangement>
</codeStyleSettings>
</code_scheme>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="PLATFORM" />
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="1.8" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="BintrayJCenter" />
<option name="name" value="BintrayJCenter" />
<option name="url" value="https://jcenter.bintray.com/" />
</remote-repository>
<remote-repository>
<option name="id" value="Google" />
<option name="name" value="Google" />
<option name="url" value="https://dl.google.com/dl/android/maven2/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
/build
\ No newline at end of file
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 30
buildToolsVersion "30.0.1"
defaultConfig {
applicationId "net.codecode.consciencefood"
minSdkVersion 28
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0'
implementation "androidx.navigation:navigation-ui-ktx:$navigationVersion"
implementation files('libs\\zing-core-3.4.0.jar')
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation "androidx.test.espresso:espresso-contrib:$espressoVersion"
androidTestImplementation 'androidx.test:rules:1.3.0-rc03'
}
\ No newline at end of file
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
\ No newline at end of file
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.codecode.consciencefood
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.testing.FragmentScenario
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.IdlingResource
import java.util.UUID
/**
* An espresso idling resource implementation that reports idle status for all data binding
* layouts. Data Binding uses a mechanism to post messages which Espresso doesn't track yet.
*
* Since this application only uses fragments, the resource only checks the fragments and their
* children instead of the whole view tree.
*/
class DataBindingIdlingResource : IdlingResource {
// list of registered callbacks
private val idlingCallbacks = mutableListOf<IdlingResource.ResourceCallback>()
// give it a unique id to workaround an espresso bug where you cannot register/unregister
// an idling resource w/ the same name.
private val id = UUID.randomUUID().toString()
// holds whether isIdle is called and the result was false. We track this to avoid calling
// onTransitionToIdle callbacks if Espresso never thought we were idle in the first place.
private var wasNotIdle = false
lateinit var activity: FragmentActivity
override fun getName() = "DataBinding $id"
override fun isIdleNow(): Boolean {
val idle = !getBindings().any { it.hasPendingBindings() }
@Suppress("LiftReturnOrAssignment")
if (idle) {
if (wasNotIdle) {
// notify observers to avoid espresso race detector
idlingCallbacks.forEach { it.onTransitionToIdle() }
}
wasNotIdle = false
} else {
wasNotIdle = true
// check next frame
activity.findViewById<View>(android.R.id.content).postDelayed({
isIdleNow
}, 16)
}
return idle
}
override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback) {
idlingCallbacks.add(callback)
}
/**
* Find all binding classes in all currently available fragments.
*/
private fun getBindings(): List<ViewDataBinding> {
val fragments = (activity as? FragmentActivity)
?.supportFragmentManager
?.fragments
val bindings =
fragments?.mapNotNull {
it.view?.getBinding()
} ?: emptyList()
val childrenBindings = fragments?.flatMap { it.childFragmentManager.fragments }
?.mapNotNull { it.view?.getBinding() } ?: emptyList()
return bindings + childrenBindings
}
}
private fun View.getBinding(): ViewDataBinding? = DataBindingUtil.getBinding(this)
/**
* Sets the activity from an [ActivityScenario] to be used from [DataBindingIdlingResource].
*/
fun DataBindingIdlingResource.monitorActivity(
activityScenario: ActivityScenario<out FragmentActivity>
) {
activityScenario.onActivity {
this.activity = it
}
}
/**
* Sets the fragment from a [FragmentScenario] to be used from [DataBindingIdlingResource].
*/
fun DataBindingIdlingResource.monitorFragment(fragmentScenario: FragmentScenario<out Fragment>) {
fragmentScenario.onFragment {
this.activity = it.requireActivity()
}
}
package net.codecode.consciencefood;
import android.preference.PreferenceActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import net.codecode.consciencefood.fragment.Gourmet_gragment;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import androidx.test.espresso.ViewInteraction;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import static androidx.test.espresso.Espresso.onData;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.longClick;
import static androidx.test.espresso.action.ViewActions.scrollTo;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withClassName;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class EatGoneTest {
@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void myOrderTest() {
ViewInteraction appCompatRadioButton = onView(
allOf(withId(R.id.main_radio1), withText("吃货驾到"),
childAtPosition(
allOf(withId(R.id.main_radioGroup),
childAtPosition(
withClassName(is("android.widget.LinearLayout")),
3)),
1),
isDisplayed()));
appCompatRadioButton.perform(click());
onData(instanceOf(Gourmet_gragment.class))
.inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0)
// .onChildView(withId(android.R.id.title))
// .check(matches(withText("General")))
.perform(longClick());
// ViewInteraction appCompatTextView = onView(
// allOf(withId(android.R.id.title), withText("收藏"),
// childAtPosition(
// childAtPosition(
// withId(android.R.id.content),
// 0),
// 0),
// isDisplayed()));
// appCompatTextView.perform(click());
// 在收藏列表中增加了一项
// ViewInteraction appCompatTextView2 = onView(
// allOf(withId(android.R.id.title), withText("微信分享"),
// childAtPosition(
// childAtPosition(
// withId(android.R.id.content),
// 0),
// 0),
// isDisplayed()));
// appCompatTextView2.perform(click());
//
// ViewInteraction appCompatButton = onView(
// allOf(withId(android.R.id.button1), withText("确定"),
// childAtPosition(
// childAtPosition(
// withClassName(is("android.widget.ScrollView")),
// 0),
// 3)));
// appCompatButton.perform(scrollTo(), click());
//
// ViewInteraction appCompatTextView3 = onView(
// allOf(withId(android.R.id.title), withText("微信分享"),
// childAtPosition(
// childAtPosition(
// withId(android.R.id.content),
// 0),
// 0),
// isDisplayed()));
// appCompatTextView3.perform(click());
//
// ViewInteraction appCompatButton2 = onView(
// allOf(withId(android.R.id.button2), withText("取消"),
// childAtPosition(
// childAtPosition(
// withClassName(is("android.widget.ScrollView")),
// 0),
// 2)));
// appCompatButton2.perform(scrollTo(), click());
ViewInteraction appCompatTextView4 = onView(
allOf(withId(android.R.id.title), withText("删除"),
childAtPosition(
childAtPosition(
withId(android.R.id.content),
0),
0),
isDisplayed()));
appCompatTextView4.perform(click());
// 查看列表项中少了一项
}
private static Matcher<View> childAtPosition(
final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup && parentMatcher.matches(parent)
&& view.equals(((ViewGroup) parent).getChildAt(position));
}
};
}
}
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.codecode.consciencefood
import androidx.test.espresso.IdlingResource
/**
* Contains a static reference to [IdlingResource], only available in the 'mock' build type.
*/
object EspressoIdlingResource {
private const val RESOURCE = "GLOBAL"
@JvmField
val countingIdlingResource = SimpleCountingIdlingResource(RESOURCE)
fun increment() {
countingIdlingResource.increment()
}
fun decrement() {
if (!countingIdlingResource.isIdleNow) {
countingIdlingResource.decrement()
}
}
}
inline fun <T> wrapEspressoIdlingResource(function: () -> T): T {
// Espresso does not work well with coroutines yet. See
// https://github.com/Kotlin/kotlinx.coroutines/issues/982
EspressoIdlingResource.increment() // Set app as busy.
return try {
function()
} finally {
EspressoIdlingResource.decrement() // Set app as idle.
}
}
package net.codecode.consciencefood;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("net.codecode.consciencefood", appContext.getPackageName());
}
}
\ No newline at end of file
package net.codecode.consciencefood
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.RootMatchers
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.*
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class HomeTest {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Test
fun homeTest() {
val appCompatRadioButton = onView(
allOf(withId(R.id.main_radio0), withText("首页"),
childAtPosition(
allOf(withId(R.id.main_radioGroup),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
3)),
0),
isDisplayed()))
appCompatRadioButton.perform(click())
val linearLayout = onData(anything())
.inAdapterView(allOf(withId(R.id.home_gridView1),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
2)))
.atPosition(0)
linearLayout.perform(click())
// onView(withText("新品驾到"))
// .inRoot(RootMatchers.withDecorView(not(mActivityTestRule.getActivity().getWindow().getDecorView())))
// .check(ViewAssertions.matches(isDisplayed()))
val linearLayout2 = onData(anything())
.inAdapterView(allOf(withId(R.id.home_gridView1),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
2)))
.atPosition(1)
linearLayout2.perform(click())
// onView(withText("食趣"))
// .inRoot(RootMatchers.withDecorView(not(mActivityTestRule.getActivity().getWindow().getDecorView())))
// .check(ViewAssertions.matches(isDisplayed()))
val linearLayout3 = onData(anything())
.inAdapterView(allOf(withId(R.id.home_gridView1),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
2)))
.atPosition(2)
linearLayout3.perform(click())
// onView(withText("食品安全"))
// .inRoot(RootMatchers.withDecorView(not(mActivityTestRule.getActivity().getWindow().getDecorView())))
// .check(ViewAssertions.matches(isDisplayed()))
val linearLayout4 = onData(anything())
.inAdapterView(allOf(withId(R.id.home_gridView1),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
2)))
.atPosition(3)
linearLayout4.perform(click())
// onView(withText("产品溯源"))
// .inRoot(RootMatchers.withDecorView(not(mActivityTestRule.getActivity().getWindow().getDecorView())))
// .check(ViewAssertions.matches(isDisplayed()))
val linearLayout5 = onData(anything())
.inAdapterView(allOf(withId(R.id.home_gridView1),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
2)))
.atPosition(4)
linearLayout5.perform(click())
// onView(withText("健康养身"))
// .inRoot(RootMatchers.withDecorView(not(mActivityTestRule.getActivity().getWindow().getDecorView())))
// .check(ViewAssertions.matches(isDisplayed()))
val linearLayout6 = onData(anything())
.inAdapterView(allOf(withId(R.id.home_gridView1),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
2)))
.atPosition(5)
linearLayout6.perform(click())
// onView(withText("产品展示"))
// .inRoot(RootMatchers.withDecorView(not(mActivityTestRule.getActivity().getWindow().getDecorView())))
// .check(ViewAssertions.matches(isDisplayed()))
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
package net.codecode.consciencefood
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers.withDecorView
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.*
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Test
fun mainActivityTest() {
val appCompatRadioButton = onView(
allOf(withId(R.id.main_radio3), withText("个人中心"),
childAtPosition(
allOf(withId(R.id.main_radioGroup),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
3)),
3),
isDisplayed()))
appCompatRadioButton.perform(click())
onView(withText("登录")).check(matches(isDisplayed()))
onView(withText("登录")).perform(click())
onView(withId(R.id.Login_editUsername)).perform(typeText("test"), closeSoftKeyboard())
onView(withId(R.id.Login_editPassword)).perform(typeText("11111111"), closeSoftKeyboard())
onView(withText("登录")).perform(click())
// Thread.sleep(1000)
onView(withText("用户名或密码不能为空"))
.inRoot(withDecorView(not(mActivityTestRule.getActivity().getWindow().getDecorView())))
.check(matches(isDisplayed()));
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
package net.codecode.consciencefood
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class MainActivityTest2 {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Test
fun mainActivityTest2() {
}
}
package net.codecode.consciencefood
import android.service.autofill.Validators.not
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class MainActivityTest3 {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Test
fun mainActivityTest3() {
val appCompatRadioButton2 = onView(
allOf(withId(R.id.main_radio0), withText("首页"),
childAtPosition(
allOf(withId(R.id.main_radioGroup),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
3)),
0),
isDisplayed()))
appCompatRadioButton2.perform(click())
val appCompatRadioButton3 = onView(
allOf(withId(R.id.main_radio1), withText("吃货驾到"),
childAtPosition(
allOf(withId(R.id.main_radioGroup),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
3)),
1),
isDisplayed()))
appCompatRadioButton3.perform(click())
val appCompatRadioButton5 = onView(
allOf(withId(R.id.main_radio2), withText("我的订单"),
childAtPosition(
allOf(withId(R.id.main_radioGroup),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
3)),
2),
isDisplayed()))
appCompatRadioButton5.perform(click())
val appCompatRadioButton6 = onView(
allOf(withId(R.id.main_radio3), withText("个人中心"),
childAtPosition(
allOf(withId(R.id.main_radioGroup),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
3)),
3),
isDisplayed()))
appCompatRadioButton6.perform(click())
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.codecode.consciencefood
import androidx.test.espresso.IdlingResource
import java.util.concurrent.atomic.AtomicInteger
/**
* An simple counter implementation of [IdlingResource] that determines idleness by
* maintaining an internal counter. When the counter is 0 - it is considered to be idle, when it is
* non-zero it is not idle. This is very similar to the way a [java.util.concurrent.Semaphore]
* behaves.
*
*
* This class can then be used to wrap up operations that while in progress should block tests from
* accessing the UI.
*/
class SimpleCountingIdlingResource(private val resourceName: String) : IdlingResource {
private val counter = AtomicInteger(0)
// written from main thread, read from any thread.
@Volatile
private var resourceCallback: IdlingResource.ResourceCallback? = null
override fun getName() = resourceName
override fun isIdleNow() = counter.get() == 0
override fun registerIdleTransitionCallback(resourceCallback: IdlingResource.ResourceCallback) {
this.resourceCallback = resourceCallback
}
/**
* Increments the count of in-flight transactions to the resource being monitored.
*/
fun increment() {
counter.getAndIncrement()
}
/**
* Decrements the count of in-flight transactions to the resource being monitored.
* If this operation results in the counter falling below 0 - an exception is raised.
*
* @throws IllegalStateException if the counter is below 0.
*/
fun decrement() {
val counterVal = counter.decrementAndGet()
if (counterVal == 0) {
// we've gone from non-zero to zero. That means we're idle now! Tell espresso.
resourceCallback?.onTransitionToIdle()
} else if (counterVal < 0) {
throw IllegalStateException("Counter has been corrupted!")
}
}
}
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.codecode.consciencefood
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import org.hamcrest.Matchers
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Large End-to-End test for the tasks module.
*
* UI tests usually use [ActivityTestRule] but there's no API to perform an action before
* each test. The workaround is to use `ActivityScenario.launch()` and `ActivityScenario.close()`.
*/
@RunWith(AndroidJUnit4::class)
@LargeTest
class ToastTest {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
// private lateinit var repository: TasksRepository
// An Idling Resource that waits for Data Binding to have no pending bindings
private val dataBindingIdlingResource = DataBindingIdlingResource()
@Before
fun init() {
// repository = ServiceLocator.provideTasksRepository(getApplicationContext())
// repository.deleteAllTasksBlocking()
}
@After
fun reset() {
// ServiceLocator.resetRepository()
}
/**
* Idling resources tell Espresso that the app is idle or busy. This is needed when operations
* are not scheduled in the main Looper (for example when executed on a different thread).
*/
@Before
fun registerIdlingResource() {
IdlingRegistry.getInstance().register(EspressoIdlingResource.countingIdlingResource)
IdlingRegistry.getInstance().register(dataBindingIdlingResource)
}
/**
* Unregister your Idling Resource so it can be garbage collected and does not leak any memory.
*/
@After
fun unregisterIdlingResource() {
IdlingRegistry.getInstance().unregister(EspressoIdlingResource.countingIdlingResource)
IdlingRegistry.getInstance().unregister(dataBindingIdlingResource)
}
@Test
fun createOneTask_deleteTask() {
// start up Tasks screen
val activityScenario = ActivityScenario.launch(MainActivity::class.java)
dataBindingIdlingResource.monitorActivity(activityScenario)
onView(Matchers.allOf(withId(R.id.main_radio0), withText("首页"), isDisplayed())).perform(click())
onView(withId(R.id.btntoast)).perform(click())
onView(withText("testtoast")).inRoot(RootMatchers.withDecorView(Matchers.not(mActivityTestRule.getActivity().getWindow().getDecorView()))).check(matches(isDisplayed()))
// Make sure the activity is closed before resetting the db:
activityScenario.close()
}
}
package net.codecode.consciencefood
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.longClick
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.*
import org.hamcrest.TypeSafeMatcher
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class UITest1 {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
private var mActivity: MainActivity? = null
@Before
fun setActivity() {
mActivity = mActivityTestRule.getActivity()
}
@Test
fun uITest1() {
// 切换到吃货驾到
val appCompatRadioButton = onView(
allOf(withId(R.id.main_radio1), withText("吃货驾到"),
childAtPosition(
allOf(withId(R.id.main_radioGroup),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
3)),
1),
isDisplayed()))
appCompatRadioButton.perform(click())
// 检查列表项中包含的控件
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).onChildView(withId(R.id.buju_gourment_pic)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).onChildView(withId(R.id.buju_gourment_count)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).onChildView(withId(R.id.buju_gourment_text)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).onChildView(withId(R.id.buju_gourment_username)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).onChildView(withId(R.id.buju_goument_time)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).onChildView(withId(R.id.buju_goument_praise)).check(matches(isDisplayed()))
// 检测点赞数量的变化
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).onChildView(withText("0")).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).onChildView(withId(R.id.buju_goument_praise)).perform(click())
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).onChildView(withText("1")).check(matches(isDisplayed()))
// 测试长按弹出菜单
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).perform(longClick())
onView(withText("微信分享"))
.inRoot(RootMatchers.withDecorView(not(`is`(mActivity?.getWindow()?.getDecorView()))))
.check(matches(isDisplayed())).perform(click())
onView(withText("确定"))
.inRoot(RootMatchers.withDecorView(not(`is`(mActivity?.getWindow()?.getDecorView()))))
.check(matches(isDisplayed())).perform(click())
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).perform(longClick())
onView(withText("微信分享"))
.inRoot(RootMatchers.withDecorView(not(`is`(mActivity?.getWindow()?.getDecorView()))))
.check(matches(isDisplayed())).perform(click())
onView(withText("取消"))
.inRoot(RootMatchers.withDecorView(not(`is`(mActivity?.getWindow()?.getDecorView()))))
.check(matches(isDisplayed())).perform(click())
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).perform(longClick())
onView(withText("收藏"))
.inRoot(RootMatchers.withDecorView(not(`is`(mActivity?.getWindow()?.getDecorView()))))
.check(matches(isDisplayed())).perform(click())
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).perform(longClick())
onView(withText("删除"))
.inRoot(RootMatchers.withDecorView(not(`is`(mActivity?.getWindow()?.getDecorView()))))
.check(matches(isDisplayed())).perform(click())
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
package net.codecode.consciencefood
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.*
import org.hamcrest.TypeSafeMatcher
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class UITest2 {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
private var mActivity: MainActivity? = null
@Before
fun setActivity() {
mActivity = mActivityTestRule.getActivity()
}
@Test
fun uITest2() {
// 切换到吃货驾到,目的是测试收藏列表中的内容
val appCompatRadioButton = onView(
allOf(withId(R.id.main_radio1), withText("吃货驾到"),
childAtPosition(
allOf(withId(R.id.main_radioGroup),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
3)),
1),
isDisplayed()))
appCompatRadioButton.perform(click())
onData(anything()).inAdapterView(withId(R.id.gourment_frag_listView1))
.atPosition(0).perform(ViewActions.longClick())
onView(withText("收藏"))
.inRoot(RootMatchers.withDecorView(not(`is`(mActivity?.getWindow()?.getDecorView()))))
.check(ViewAssertions.matches(isDisplayed())).perform(click())
// 切换到我的订单
val appCompatRadioButton2 = onView(
allOf(withId(R.id.main_radio2), withText("我的订单"),
childAtPosition(
allOf(withId(R.id.main_radioGroup),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
3)),
2),
isDisplayed()))
appCompatRadioButton2.perform(click())
// 测试每一个订单项包含的内容
onData(anything()).inAdapterView(withId(R.id.frag_order_orderList)).atPosition(0)
.onChildView(withId(R.id.buju_orderList_pic)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.frag_order_orderList)).atPosition(0)
.onChildView(withId(R.id.buju_orderList_name)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.frag_order_orderList)).atPosition(0)
.onChildView(withId(R.id.buju_orderList_address)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.frag_order_orderList)).atPosition(0)
.onChildView(withId(R.id.buju_orderList_price)).check(matches(isDisplayed()))
// 测试每一个收藏项包含的内容
onData(anything()).inAdapterView(withId(R.id.frag_order_collectionList)).atPosition(0)
.onChildView(withId(R.id.buju_order_collection_pic)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.frag_order_collectionList)).atPosition(0)
.onChildView(withId(R.id.buju_order_collection_text)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.frag_order_collectionList)).atPosition(0)
.onChildView(withId(R.id.buju_order_collection_username)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.frag_order_collectionList)).atPosition(0)
.onChildView(withId(R.id.buju_order_collection_time)).check(matches(isDisplayed()))
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
package net.codecode.consciencefood
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class UITest3 {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Test
fun uITest3() {
val appCompatRadioButton = onView(
allOf(withId(R.id.main_radio3), withText("个人中心"),
childAtPosition(
allOf(withId(R.id.main_radioGroup),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
3)),
3),
isDisplayed()))
appCompatRadioButton.perform(click())
// 测试显示的控件
onView(withId(R.id.imageView)).check(matches(isDisplayed()))
onView(withId(R.id.textView)).check(matches(isDisplayed()))
onView(withId(R.id.imageView2)).check(matches(isDisplayed()))
onView(withId(R.id.textView2)).check(matches(isDisplayed()))
onView(withId(R.id.imageView3)).check(matches(isDisplayed()))
onView(withId(R.id.textView3)).check(matches(isDisplayed()))
onView(withId(R.id.imageView4)).check(matches(isDisplayed()))
onView(withId(R.id.textView4)).check(matches(isDisplayed()))
onView(withId(R.id.imageView5)).check(matches(isDisplayed()))
onView(withId(R.id.textView5)).check(matches(isDisplayed()))
onView(withId(R.id.imageView6)).check(matches(isDisplayed()))
onView(withId(R.id.textView6)).check(matches(isDisplayed()))
onView(withId(R.id.imageView7)).check(matches(isDisplayed()))
onView(withId(R.id.textView7)).check(matches(isDisplayed()))
onView(withId(R.id.nextimageView7)).check(matches(isDisplayed()))
// 点击“登录”按钮,跳转到登录窗口
onView(allOf(withId(R.id.btnLogin), isDisplayed())).perform(click())
// 点击“关闭”按钮,关闭登录窗口
onView(allOf(withId(R.id.close_login), isDisplayed())).perform(click())
// 点击“更多”按钮,跳转到更多页面
onView(allOf(withId(R.id.nextimageView7), isDisplayed())).perform(click())
// 测试在“更多”窗口中显示的控件
onView(withId(R.id.imageView1)).check(matches(isDisplayed()))
onView(withId(R.id.textView1)).check(matches(isDisplayed()))
onView(withId(R.id.weatherdetail)).check(matches(isDisplayed()))
onView(withId(R.id.imageView2)).check(matches(isDisplayed()))
onView(withId(R.id.textView2)).check(matches(isDisplayed()))
onView(withId(R.id.positiondetail)).check(matches(isDisplayed()))
onView(withId(R.id.imageView3)).check(matches(isDisplayed()))
onView(withId(R.id.textView3)).check(matches(isDisplayed()))
onView(withId(R.id.scandetail)).check(matches(isDisplayed()))
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
package net.codecode.consciencefood
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class UITest4 {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Test
fun uITest4() {
val appCompatRadioButton = onView(
allOf(withId(R.id.main_radio3), withText("个人中心"),
childAtPosition(
allOf(withId(R.id.main_radioGroup),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
3)),
3),
isDisplayed()))
appCompatRadioButton.perform(click())
onView(allOf(withId(R.id.btnLogin), isDisplayed())).perform(click())
// 测试在登录窗口输入用户名和密码
onView(allOf(withId(R.id.Login_editUsername), isDisplayed())).perform(replaceText("test"), closeSoftKeyboard())
onView(allOf(withId(R.id.Login_editUsername), withText("test"), isDisplayed())).perform(pressImeActionButton())
onView(allOf(withId(R.id.Login_editPassword), isDisplayed())).perform(replaceText("11111111"), closeSoftKeyboard())
onView(allOf(withId(R.id.Login_editPassword), withText("11111111"), isDisplayed())).perform(pressImeActionButton())
onView(allOf(withId(R.id.Login_btnLoginup), isDisplayed())).perform(click())
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
package net.codecode.consciencefood
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.*
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class UITest5 {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Test
fun uITest5() {
onView(allOf(withId(R.id.main_radio3), withText("个人中心"), isDisplayed())).perform(click())
onView(allOf(withId(R.id.nextimageView7), isDisplayed())).perform(click())
onView(allOf(withId(R.id.weatherdetail), isDisplayed())).perform(click())
onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).
onChildView(withId(R.id.cityValue)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).
onChildView(withId(R.id.lowest_temperature_value)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).
onChildView(withId(R.id.highest_temperature)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).
onChildView(withId(R.id.win_value)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).
onChildView(withId(R.id.wea_value)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).
onChildView(withId(R.id.air_level_value)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).
onChildView(withId(R.id.pm25_value)).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.list)).atPosition(0).
onChildView(withId(R.id.visibility_value)).check(matches(isDisplayed()))
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
package net.codecode.consciencefood
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.rule.GrantPermissionRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class UITest6 {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Rule
@JvmField
var mGrantPermissionRule =
GrantPermissionRule.grant(
"android.permission.ACCESS_FINE_LOCATION")
@Test
fun uITest6() {
onView(allOf(withId(R.id.main_radio3), withText("个人中心"), isDisplayed())).perform(click())
onView(allOf(withId(R.id.nextimageView7),isDisplayed())).perform(click())
onView(allOf(withId(R.id.positiondetail), isDisplayed())).perform(click())
Espresso.onData(Matchers.anything()).inAdapterView(withId(R.id.list)).atPosition(0).
onChildView(withId(R.id.longitude_value)).check(ViewAssertions.matches(isDisplayed()))
Espresso.onData(Matchers.anything()).inAdapterView(withId(R.id.list)).atPosition(0).
onChildView(withId(R.id.latitude_value)).check(ViewAssertions.matches(isDisplayed()))
Espresso.onData(Matchers.anything()).inAdapterView(withId(R.id.list)).atPosition(0).
onChildView(withId(R.id.altitude_value)).check(ViewAssertions.matches(isDisplayed()))
Espresso.onData(Matchers.anything()).inAdapterView(withId(R.id.list)).atPosition(0).
onChildView(withId(R.id.accuracy_value)).check(ViewAssertions.matches(isDisplayed()))
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
package net.codecode.consciencefood
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.rule.GrantPermissionRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class UITest7 {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Rule
@JvmField
var mGrantPermissionRule =
GrantPermissionRule.grant(
"android.permission.CAMERA")
@Test
fun uITest7() {
onView(allOf(withId(R.id.main_radio3), withText("个人中心"),isDisplayed())).perform(click())
onView(allOf(withId(R.id.nextimageView7),isDisplayed())).perform(click())
onView(allOf(withId(R.id.scandetail),isDisplayed())).perform(click())
// onView(allOf(withId(R.id.btn_album), isDisplayed())).perform(click())
// val button = onView(
// allOf(withId(R.id.btn_album), withText("相册"),
// childAtPosition(
// childAtPosition(
// withId(R.id.toolbar),
// 0),
// 2),
// isDisplayed()))
// button.perform(click())
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
package net.codecode.consciencefood
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers.withDecorView
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.rule.ActivityTestRule
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.*
import org.hamcrest.core.IsNot.not
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class UITest8 {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Test
fun uITest() {
onData(anything()).inAdapterView(withId(R.id.home_gridView1)).atPosition(0).check(matches(isDisplayed()))
onView(withText("新品驾到")).inRoot(withDecorView(not(mActivityTestRule.getActivity().getWindow().getDecorView()))).check(matches(isDisplayed()))
}
@Test
fun uITest8() {
// 切换到首页
onView(allOf(withId(R.id.main_radio0), withText("首页"), isDisplayed())).perform(click())
// 测试首页轮播效果
onView(allOf(withId(R.id.home_viewpager), isDisplayed())).perform(ViewActions.swipeLeft(), ViewActions.swipeLeft())
onView(allOf(withId(R.id.home_viewpager), isDisplayed())).perform(ViewActions.swipeRight(), ViewActions.swipeRight())
onData(anything()).inAdapterView(withId(R.id.home_gridView1)).atPosition(0).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.home_gridView1)).atPosition(1).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.home_gridView1)).atPosition(2).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.home_gridView1)).atPosition(3).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.home_gridView1)).atPosition(4).check(matches(isDisplayed()))
onData(anything()).inAdapterView(withId(R.id.home_gridView1)).atPosition(5).check(matches(isDisplayed()))
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.codecode.consciencefood">
<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>
<activity android:name=".LoginActivity">
</activity>
<activity android:name=".LocationActivity" />
<activity android:name=".MoreActivity" />
<activity android:name=".FindScanActivity"/>
<activity android:name=".ScanResultActivity"/>
<activity android:name=".WeatherForecastActivity"/>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<!-- 定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 拍照 -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<!-- 录像/录音 -->
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- 震动 -->
<uses-permission android:name="android.permission.VIBRATE" />
</manifest>
\ No newline at end of file
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.camera;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
final class AutoFocusCallback implements Camera.AutoFocusCallback {
private static final String TAG = AutoFocusCallback.class.getSimpleName();
private static final long AUTOFOCUS_INTERVAL_MS = 1500L;
private Handler autoFocusHandler;
private int autoFocusMessage;
void setHandler(Handler autoFocusHandler, int autoFocusMessage) {
this.autoFocusHandler = autoFocusHandler;
this.autoFocusMessage = autoFocusMessage;
}
public void onAutoFocus(boolean success, Camera camera) {
if (autoFocusHandler != null) {
Message message = autoFocusHandler.obtainMessage(autoFocusMessage, success);
autoFocusHandler.sendMessageDelayed(message, AUTOFOCUS_INTERVAL_MS);
autoFocusHandler = null;
} else {
Log.d(TAG, "Got auto-focus callback, but no handler for it");
}
}
}
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.camera;
import android.content.Context;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Build;
import android.util.Log;
import net.codecode.consciencefood.util.CameraUtil;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
final class CameraConfigurationManager {
private static final String TAG = CameraConfigurationManager.class.getSimpleName();
private static final int TEN_DESIRED_ZOOM = 27;
private static final int DESIRED_SHARPNESS = 30;
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
private final Context context;
private Point screenResolution;
private Point cameraResolution;
private int previewFormat;
private String previewFormatString;
CameraConfigurationManager(Context context) {
this.context = context;
}
/**
* Reads, one time, values from the camera that are needed by the app.
*/
void initFromCameraParameters(Camera camera) {
Camera.Parameters parameters = camera.getParameters();
previewFormat = parameters.getPreviewFormat();
previewFormatString = parameters.get("preview-format");
Log.d(TAG, "Default preview format: " + previewFormat + '/' + previewFormatString);
screenResolution = CameraUtil.getSize(context);
Log.d(TAG, "Screen resolution: " + screenResolution);
//cameraResolution = getCameraResolution(parameters, screenResolution);
cameraResolution = CameraUtil.getCameraSize(parameters, screenResolution);
Log.d(TAG, "Camera resolution: " + cameraResolution);
}
/**
* Sets the camera up to take preview images which are used for both preview and decoding.
* We detect the preview format here so that buildLuminanceSource() can build an appropriate
* LuminanceSource subclass. In the future we may want to force YUV420SP as it's the smallest,
* and the planar Y can be used for barcode scanning without a copy in some cases.
*/
void setDesiredCameraParameters(Camera camera) {
Camera.Parameters parameters = camera.getParameters();
Log.d(TAG, "Setting preview size: " + cameraResolution);
parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
setFlash(parameters);
setZoom(parameters);
//setSharpness(parameters);
//modify here
// camera.setDisplayOrientation(90);
//����2.1
setDisplayOrientation(camera, 90);
camera.setParameters(parameters);
}
Point getCameraResolution() {
return cameraResolution;
}
Point getScreenResolution() {
return screenResolution;
}
int getPreviewFormat() {
return previewFormat;
}
String getPreviewFormatString() {
return previewFormatString;
}
// private static Point getCameraResolution(Camera.Parameters parameters, Point screenResolution) {
//
// String previewSizeValueString = parameters.get("preview-size-values");
// // saw this on Xperia
// if (previewSizeValueString == null) {
// previewSizeValueString = parameters.get("preview-size-value");
// }
//
// Point cameraResolution = null;
//
// if (previewSizeValueString != null) {
// Log.d(TAG, "preview-size-values parameter: " + previewSizeValueString);
// cameraResolution = findBestPreviewSizeValue(previewSizeValueString, screenResolution);
// }
//
// if (cameraResolution == null) {
// // Ensure that the camera resolution is a multiple of 8, as the screen may not be.
// cameraResolution = new Point(
// (screenResolution.x >> 3) << 3,
// (screenResolution.y >> 3) << 3);
// }
//
// return cameraResolution;
// }
//
// private static Point findBestPreviewSizeValue(CharSequence previewSizeValueString, Point screenResolution) {
// int bestX = 0;
// int bestY = 0;
// int diff = Integer.MAX_VALUE;
// for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) {
//
// previewSize = previewSize.trim();
// int dimPosition = previewSize.indexOf('x');
// if (dimPosition < 0) {
// Log.w(TAG, "Bad preview-size: " + previewSize);
// continue;
// }
//
// int newX;
// int newY;
// try {
// newX = Integer.parseInt(previewSize.substring(0, dimPosition));
// newY = Integer.parseInt(previewSize.substring(dimPosition + 1));
// } catch (NumberFormatException nfe) {
// Log.w(TAG, "Bad preview-size: " + previewSize);
// continue;
// }
//
// //int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y);
// int newDiff = Math.abs((newX - screenResolution.x) + (newY - screenResolution.y));
// if (newDiff == 0) {
// bestX = newX;
// bestY = newY;
// break;
// } else if (newDiff < diff) {
// bestX = newX;
// bestY = newY;
// diff = newDiff;
// }
//
// }
//
// if (bestX > 0 && bestY > 0) {
// return new Point(bestX, bestY);
// }
// return null;
// }
private static int findBestMotZoomValue(CharSequence stringValues, int tenDesiredZoom) {
int tenBestValue = 0;
for (String stringValue : COMMA_PATTERN.split(stringValues)) {
stringValue = stringValue.trim();
double value;
try {
value = Double.parseDouble(stringValue);
} catch (NumberFormatException nfe) {
return tenDesiredZoom;
}
int tenValue = (int) (10.0 * value);
if (Math.abs(tenDesiredZoom - value) < Math.abs(tenDesiredZoom - tenBestValue)) {
tenBestValue = tenValue;
}
}
return tenBestValue;
}
private void setFlash(Camera.Parameters parameters) {
// FIXME: This is a hack to turn the flash off on the Samsung Galaxy.
// And this is a hack-hack to work around a different value on the Behold II
// Restrict Behold II check to Cupcake, per Samsung's advice
//if (Build.MODEL.contains("Behold II") &&
// CameraManager.SDK_INT == Build.VERSION_CODES.CUPCAKE) {
if (Build.MODEL.contains("Behold II") && CameraManager.SDK_INT == 3) { // 3 = Cupcake
parameters.set("flash-value", 1);
} else {
parameters.set("flash-value", 2);
}
// This is the standard setting to turn the flash off that all devices should honor.
parameters.set("flash-mode", "off");
}
private void setZoom(Camera.Parameters parameters) {
String zoomSupportedString = parameters.get("zoom-supported");
if (zoomSupportedString != null && !Boolean.parseBoolean(zoomSupportedString)) {
return;
}
int tenDesiredZoom = TEN_DESIRED_ZOOM;
String maxZoomString = parameters.get("max-zoom");
if (maxZoomString != null) {
try {
int tenMaxZoom = (int) (10.0 * Double.parseDouble(maxZoomString));
if (tenDesiredZoom > tenMaxZoom) {
tenDesiredZoom = tenMaxZoom;
}
} catch (NumberFormatException nfe) {
Log.w(TAG, "Bad max-zoom: " + maxZoomString);
}
}
String takingPictureZoomMaxString = parameters.get("taking-picture-zoom-max");
if (takingPictureZoomMaxString != null) {
try {
int tenMaxZoom = Integer.parseInt(takingPictureZoomMaxString);
if (tenDesiredZoom > tenMaxZoom) {
tenDesiredZoom = tenMaxZoom;
}
} catch (NumberFormatException nfe) {
Log.w(TAG, "Bad taking-picture-zoom-max: " + takingPictureZoomMaxString);
}
}
String motZoomValuesString = parameters.get("mot-zoom-values");
if (motZoomValuesString != null) {
tenDesiredZoom = findBestMotZoomValue(motZoomValuesString, tenDesiredZoom);
}
String motZoomStepString = parameters.get("mot-zoom-step");
if (motZoomStepString != null) {
try {
double motZoomStep = Double.parseDouble(motZoomStepString.trim());
int tenZoomStep = (int) (10.0 * motZoomStep);
if (tenZoomStep > 1) {
tenDesiredZoom -= tenDesiredZoom % tenZoomStep;
}
} catch (NumberFormatException nfe) {
// continue
}
}
// Set zoom. This helps encourage the user to pull back.
// Some devices like the Behold have a zoom parameter
if (maxZoomString != null || motZoomValuesString != null) {
parameters.set("zoom", String.valueOf(tenDesiredZoom / 10.0));
}
// Most devices, like the Hero, appear to expose this zoom parameter.
// It takes on values like "27" which appears to mean 2.7x zoom
if (takingPictureZoomMaxString != null) {
parameters.set("taking-picture-zoom", tenDesiredZoom);
}
}
public static int getDesiredSharpness() {
return DESIRED_SHARPNESS;
}
/**
* compatible 1.6
*
* @param camera
* @param angle
*/
protected void setDisplayOrientation(Camera camera, int angle) {
Method downPolymorphic;
try {
downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[]{int.class});
if (downPolymorphic != null)
downPolymorphic.invoke(camera, new Object[]{angle});
} catch (Exception e1) {
}
}
}
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.camera;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import net.codecode.consciencefood.util.CameraUtil;
import java.io.IOException;
/**
* This object wraps the Camera service object and expects to be the only one talking to it. The
* implementation encapsulates the steps needed to take preview-sized images, which are used for
* both preview and decoding.
*/
public final class CameraManager {
private static final String TAG = CameraManager.class.getSimpleName();
private static final int MIN_FRAME_WIDTH = 240;
private static final int MIN_FRAME_HEIGHT = 240;
private static final int MAX_FRAME_WIDTH = 480;
private static final int MAX_FRAME_HEIGHT = 360;
public static int BAR_CODE = 0;
public static int QR_CODE = 1;
private int mScanMode = QR_CODE;
private static CameraManager cameraManager;
static final int SDK_INT; // Later we can use Build.VERSION.SDK_INT
static {
int sdkInt;
try {
sdkInt = Build.VERSION.SDK_INT;
} catch (NumberFormatException nfe) {
// Just to be safe
sdkInt = 10000;
}
SDK_INT = sdkInt;
}
private final Context context;
private final CameraConfigurationManager configManager;
private Camera camera;
private Rect framingRect;
private Rect framingRectInPreview;
private boolean initialized;
private boolean previewing;
private final boolean useOneShotPreviewCallback;
/**
* Preview frames are delivered here, which we pass on to the registered handler. Make sure to
* clear the handler so it will only receive one message.
*/
private final PreviewCallback previewCallback;
/**
* Autofocus callbacks arrive here, and are dispatched to the Handler which requested them.
*/
private final AutoFocusCallback autoFocusCallback;
/**
* Initializes this static object with the Context of the calling Activity.
*
* @param context The Activity which wants to use the camera.
*/
public static void init(Context context, int mode) {
if (cameraManager == null) {
cameraManager = new CameraManager(context);
cameraManager.mScanMode = mode;
}
}
/**
* Gets the CameraManager singleton instance.
*
* @return A reference to the CameraManager singleton.
*/
public static CameraManager get() {
return cameraManager;
}
private CameraManager(Context context) {
this.context = context;
this.configManager = new CameraConfigurationManager(context);
// Camera.setOneShotPreviewCallback() has a race condition in Cupcake, so we use the older
// Camera.setPreviewCallback() on 1.5 and earlier. For Donut and later, we need to use
// the more efficient one shot callback, as the older one can swamp the system and cause it
// to run out of memory. We can't use SDK_INT because it was introduced in the Donut SDK.
//useOneShotPreviewCallback = Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.CUPCAKE;
useOneShotPreviewCallback = Build.VERSION.SDK_INT > 3; // 3 = Cupcake
previewCallback = new PreviewCallback(configManager, useOneShotPreviewCallback);
autoFocusCallback = new AutoFocusCallback();
}
/**
* Opens the camera driver and initializes the hardware parameters.
*
* @param holder The surface object which the camera will draw preview frames into.
* @throws IOException Indicates the camera driver failed to open.
*/
public void openDriver(SurfaceHolder holder) throws IOException {
if (camera == null) {
camera = Camera.open();
if (camera == null) {
throw new IOException();
}
camera.setPreviewDisplay(holder);
if (!initialized) {
initialized = true;
configManager.initFromCameraParameters(camera);
}
configManager.setDesiredCameraParameters(camera);
//FIXME
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
//�Ƿ�ʹ��ǰ��
// if (prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false)) {
// FlashlightManager.enableFlashlight();
// }
FlashlightManager.enableFlashlight();
}
}
/**
* Closes the camera driver if still in use.
*/
public void closeDriver() {
if (camera != null) {
FlashlightManager.disableFlashlight();
camera.release();
camera = null;
}
}
/**
* Asks the camera hardware to begin drawing preview frames to the screen.
*/
public void startPreview() {
if (camera != null && !previewing) {
camera.startPreview();
previewing = true;
}
}
/**
* Tells the camera to stop drawing preview frames.
*/
public void stopPreview() {
if (camera != null && previewing) {
if (!useOneShotPreviewCallback) {
camera.setPreviewCallback(null);
}
camera.stopPreview();
previewCallback.setHandler(null, 0);
autoFocusCallback.setHandler(null, 0);
previewing = false;
}
}
/**
* A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
* in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
* respectively.
*
* @param handler The handler to send the message to.
* @param message The what field of the message to be sent.
*/
public void requestPreviewFrame(Handler handler, int message) {
if (camera != null && previewing) {
previewCallback.setHandler(handler, message);
if (useOneShotPreviewCallback) {
camera.setOneShotPreviewCallback(previewCallback);
} else {
camera.setPreviewCallback(previewCallback);
}
}
}
/**
* Asks the camera hardware to perform an autofocus.
*
* @param handler The Handler to notify when the autofocus completes.
* @param message The message to deliver.
*/
public void requestAutoFocus(Handler handler, int message) {
if (camera != null && previewing) {
autoFocusCallback.setHandler(handler, message);
//Log.d(TAG, "Requesting auto-focus callback");
camera.autoFocus(autoFocusCallback);
}
}
/**
* Calculates the framing rect which the UI should draw to show the user where to place the
* barcode. This target helps with alignment as well as forces the user to hold the device
* far enough away to ensure the image will be in focus.
*
* @return The rectangle to draw on screen in window coordinates.
*/
public Rect getFramingRect() {
Point screenResolution = configManager.getScreenResolution();
if (framingRect == null) {
if (camera == null) {
return null;
}
int width, height;
if (mScanMode == QR_CODE) {
Point size = CameraUtil.getSize(context);
width = (int) (size.x * 0.8);
height = width;
} else {
width = screenResolution.x * 3 / 4;
if (width < MIN_FRAME_WIDTH) {
width = MIN_FRAME_WIDTH;
} else if (width > MAX_FRAME_WIDTH) {
width = MAX_FRAME_WIDTH;
}
height = screenResolution.y * 3 / 4;
if (height < MIN_FRAME_HEIGHT) {
height = MIN_FRAME_HEIGHT;
} else if (height > MAX_FRAME_HEIGHT) {
height = MAX_FRAME_HEIGHT;
}
}
int leftOffset = (screenResolution.x - width) / 2;
int topOffset = (screenResolution.y - height) / 2;
framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
Log.d(TAG, "Calculated framing rect: " + framingRect);
}
return framingRect;
}
/**
* Like {@link #getFramingRect} but coordinates are in terms of the preview frame,
* not UI / screen.
*/
public Rect getFramingRectInPreview() {
if (framingRectInPreview == null) {
Rect rect = new Rect(getFramingRect());
Point cameraResolution = configManager.getCameraResolution();
Point screenResolution = configManager.getScreenResolution();
//modify here
// rect.left = rect.left * cameraResolution.x / screenResolution.x;
// rect.right = rect.right * cameraResolution.x / screenResolution.x;
// rect.top = rect.top * cameraResolution.y / screenResolution.y;
// rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y;
rect.left = rect.left * cameraResolution.y / screenResolution.x;
rect.right = rect.right * cameraResolution.y / screenResolution.x;
rect.top = rect.top * cameraResolution.x / screenResolution.y;
rect.bottom = rect.bottom * cameraResolution.x / screenResolution.y;
framingRectInPreview = rect;
}
return framingRectInPreview;
}
/**
* Converts the result points from still resolution coordinates to screen coordinates.
*
* @param points The points returned by the Reader subclass through Result.getResultPoints().
* @return An array of Points scaled to the size of the framing rect and offset appropriately
* so they can be drawn in screen coordinates.
*/
/*
public Point[] convertResultPoints(ResultPoint[] points) {
Rect frame = getFramingRectInPreview();
int count = points.length;
Point[] output = new Point[count];
for (int x = 0; x < count; x++) {
output[x] = new Point();
output[x].x = frame.left + (int) (points[x].getX() + 0.5f);
output[x].y = frame.top + (int) (points[x].getY() + 0.5f);
}
return output;
}
*/
/**
* A factory method to build the appropriate LuminanceSource object based on the format
* of the preview buffers, as described by Camera.Parameters.
*
* @param data A preview frame.
* @param width The width of the image.
* @param height The height of the image.
* @return A PlanarYUVLuminanceSource instance.
*/
public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
Rect rect = getFramingRectInPreview();
int previewFormat = configManager.getPreviewFormat();
String previewFormatString = configManager.getPreviewFormatString();
switch (previewFormat) {
// This is the standard Android format which all devices are REQUIRED to support.
// In theory, it's the only one we should ever care about.
//case PixelFormat.YCbCr_420_SP:
case ImageFormat.NV21:
// This format has never been seen in the wild, but is compatible as we only care
// about the Y channel, so allow it.
//case PixelFormat.YCbCr_422_SP:
case ImageFormat.NV16:
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height());
default:
// The Samsung Moment incorrectly uses this variant instead of the 'sp' version.
// Fortunately, it too has all the Y data up front, so we can read it.
if ("yuv420p".equals(previewFormatString)) {
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height());
}
}
throw new IllegalArgumentException("Unsupported picture format: " +
previewFormat + '/' + previewFormatString);
}
public Context getContext() {
return context;
}
}
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.camera;
import android.os.IBinder;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* This class is used to activate the weak light on some camera phones (not flash)
* in order to illuminate surfaces for scanning. There is no official way to do this,
* but, classes which allow access to this function still exist on some devices.
* This therefore proceeds through a great deal of reflection.
* <p>
* See <a href="http://almondmendoza.com/2009/01/05/changing-the-screen-brightness-programatically/">
* http://almondmendoza.com/2009/01/05/changing-the-screen-brightness-programatically/</a> and
* <a href="http://code.google.com/p/droidled/source/browse/trunk/src/com/droidled/demo/DroidLED.java">
* http://code.google.com/p/droidled/source/browse/trunk/src/com/droidled/demo/DroidLED.java</a>.
* Thanks to Ryan Alford for pointing out the availability of this class.
*/
final class FlashlightManager {
private static final String TAG = FlashlightManager.class.getSimpleName();
private static final Object iHardwareService;
private static final Method setFlashEnabledMethod;
static {
iHardwareService = getHardwareService();
setFlashEnabledMethod = getSetFlashEnabledMethod(iHardwareService);
if (iHardwareService == null) {
Log.v(TAG, "This device does supports control of a flashlight");
} else {
Log.v(TAG, "This device does not support control of a flashlight");
}
}
private FlashlightManager() {
}
/**
* �����������ƿ���
*/
//FIXME
static void enableFlashlight() {
setFlashlight(false);
}
static void disableFlashlight() {
setFlashlight(false);
}
private static Object getHardwareService() {
Class<?> serviceManagerClass = maybeForName("android.os.ServiceManager");
if (serviceManagerClass == null) {
return null;
}
Method getServiceMethod = maybeGetMethod(serviceManagerClass, "getService", String.class);
if (getServiceMethod == null) {
return null;
}
Object hardwareService = invoke(getServiceMethod, null, "hardware");
if (hardwareService == null) {
return null;
}
Class<?> iHardwareServiceStubClass = maybeForName("android.os.IHardwareService$Stub");
if (iHardwareServiceStubClass == null) {
return null;
}
Method asInterfaceMethod = maybeGetMethod(iHardwareServiceStubClass, "asInterface", IBinder.class);
if (asInterfaceMethod == null) {
return null;
}
return invoke(asInterfaceMethod, null, hardwareService);
}
private static Method getSetFlashEnabledMethod(Object iHardwareService) {
if (iHardwareService == null) {
return null;
}
Class<?> proxyClass = iHardwareService.getClass();
return maybeGetMethod(proxyClass, "setFlashlightEnabled", boolean.class);
}
private static Class<?> maybeForName(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException cnfe) {
// OK
return null;
} catch (RuntimeException re) {
Log.w(TAG, "Unexpected error while finding class " + name, re);
return null;
}
}
private static Method maybeGetMethod(Class<?> clazz, String name, Class<?>... argClasses) {
try {
return clazz.getMethod(name, argClasses);
} catch (NoSuchMethodException nsme) {
// OK
return null;
} catch (RuntimeException re) {
Log.w(TAG, "Unexpected error while finding method " + name, re);
return null;
}
}
private static Object invoke(Method method, Object instance, Object... args) {
try {
return method.invoke(instance, args);
} catch (IllegalAccessException e) {
Log.w(TAG, "Unexpected error while invoking " + method, e);
return null;
} catch (InvocationTargetException e) {
Log.w(TAG, "Unexpected error while invoking " + method, e.getCause());
return null;
} catch (RuntimeException re) {
Log.w(TAG, "Unexpected error while invoking " + method, re);
return null;
}
}
private static void setFlashlight(boolean active) {
if (iHardwareService != null) {
invoke(setFlashEnabledMethod, iHardwareService, active);
}
}
}
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.camera;
import android.graphics.Bitmap;
import com.google.zxing.LuminanceSource;
/**
* This object extends LuminanceSource around an array of YUV data returned from the camera driver,
* with the option to crop to a rectangle within the full data. This can be used to exclude
* superfluous pixels around the perimeter and speed up decoding.
* <p>
* It works for any pixel format where the Y channel is planar and appears first, including
* YCbCr_420_SP and YCbCr_422_SP.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class PlanarYUVLuminanceSource extends LuminanceSource {
private final byte[] yuvData;
private final int dataWidth;
private final int dataHeight;
private final int left;
private final int top;
public PlanarYUVLuminanceSource(byte[] yuvData, int dataWidth, int dataHeight, int left, int top,
int width, int height) {
super(width, height);
if (left + width > dataWidth || top + height > dataHeight) {
throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
}
this.yuvData = yuvData;
this.dataWidth = dataWidth;
this.dataHeight = dataHeight;
this.left = left;
this.top = top;
}
@Override
public byte[] getRow(int y, byte[] row) {
if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException("Requested row is outside the image: " + y);
}
int width = getWidth();
if (row == null || row.length < width) {
row = new byte[width];
}
int offset = (y + top) * dataWidth + left;
System.arraycopy(yuvData, offset, row, 0, width);
return row;
}
@Override
public byte[] getMatrix() {
int width = getWidth();
int height = getHeight();
// If the caller asks for the entire underlying image, save the copy and give them the
// original data. The docs specifically warn that result.length must be ignored.
if (width == dataWidth && height == dataHeight) {
return yuvData;
}
int area = width * height;
byte[] matrix = new byte[area];
int inputOffset = top * dataWidth + left;
// If the width matches the full width of the underlying data, perform a single copy.
if (width == dataWidth) {
System.arraycopy(yuvData, inputOffset, matrix, 0, area);
return matrix;
}
// Otherwise copy one cropped row at a time.
byte[] yuv = yuvData;
for (int y = 0; y < height; y++) {
int outputOffset = y * width;
System.arraycopy(yuv, inputOffset, matrix, outputOffset, width);
inputOffset += dataWidth;
}
return matrix;
}
@Override
public boolean isCropSupported() {
return true;
}
public int getDataWidth() {
return dataWidth;
}
public int getDataHeight() {
return dataHeight;
}
public Bitmap renderCroppedGreyscaleBitmap() {
int width = getWidth();
int height = getHeight();
int[] pixels = new int[width * height];
byte[] yuv = yuvData;
int inputOffset = top * dataWidth + left;
for (int y = 0; y < height; y++) {
int outputOffset = y * width;
for (int x = 0; x < width; x++) {
int grey = yuv[inputOffset + x] & 0xff;
pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101);
}
inputOffset += dataWidth;
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
}
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.camera;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
final class PreviewCallback implements Camera.PreviewCallback {
private static final String TAG = PreviewCallback.class.getSimpleName();
private final CameraConfigurationManager configManager;
private final boolean useOneShotPreviewCallback;
private Handler previewHandler;
private int previewMessage;
PreviewCallback(CameraConfigurationManager configManager, boolean useOneShotPreviewCallback) {
this.configManager = configManager;
this.useOneShotPreviewCallback = useOneShotPreviewCallback;
}
void setHandler(Handler previewHandler, int previewMessage) {
this.previewHandler = previewHandler;
this.previewMessage = previewMessage;
}
public void onPreviewFrame(byte[] data, Camera camera) {
Point cameraResolution = configManager.getCameraResolution();
if (!useOneShotPreviewCallback) {
camera.setPreviewCallback(null);
}
if (previewHandler != null) {
Message message = previewHandler.obtainMessage(previewMessage, cameraResolution.x,
cameraResolution.y, data);
message.sendToTarget();
previewHandler = null;
} else {
Log.d(TAG, "Got preview callback, but no handler for it");
}
}
}
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.decoding;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import net.app.zxing.camera.CameraManager;
import net.app.zxing.view.ViewfinderResultPointCallback;
import net.codecode.consciencefood.FindScanActivity;
import net.codecode.consciencefood.R;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import java.util.Vector;
/**
* This class handles all the messaging which comprises the state machine for
* capture.
*/
public final class CaptureActivityHandler extends Handler {
private static final String TAG = CaptureActivityHandler.class.getSimpleName();
private final FindScanActivity activity;
private final DecodeThread decodeThread;
private State state;
private enum State {
PREVIEW, SUCCESS, DONE
}
public CaptureActivityHandler(FindScanActivity activity,
Vector<BarcodeFormat> decodeFormats, String characterSet) {
this.activity = activity;
decodeThread = new DecodeThread(activity, decodeFormats, characterSet,
new ViewfinderResultPointCallback(activity.getViewfinderView()));
decodeThread.start();
state = State.SUCCESS;
// Start ourselves capturing previews and decoding.
CameraManager.get().startPreview();
restartPreviewAndDecode();
}
@Override
public void handleMessage(Message message) {
switch (message.what) {
case R.id.auto_focus:
// Log.d(TAG, "Got auto-focus message");
// When one auto focus pass finishes, start another. This is the
// closest thing to
// continuous AF. It does seem to hunt a bit, but I'm not sure what
// else to do.
if (state == State.PREVIEW) {
CameraManager.get().requestAutoFocus(this, R.id.auto_focus);
}
break;
case R.id.restart_preview:
Log.d(TAG, "Got restart preview message");
restartPreviewAndDecode();
break;
case R.id.decode_succeeded:
Log.d(TAG, "Got decode succeeded message");
state = State.SUCCESS;
Bundle bundle = message.getData();
Bitmap barcode = bundle == null ? null : (Bitmap) bundle
.getParcelable(DecodeThread.BARCODE_BITMAP);
activity.handleDecode((Result) message.obj, barcode);
break;
case R.id.decode_failed:
// We're decoding as fast as possible, so when one decode fails,
// start another.
state = State.PREVIEW;
CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), R.id.decode);
break;
case R.id.return_scan_result:
Log.d(TAG, "Got return scan result message");
activity.setResult(Activity.RESULT_OK, (Intent) message.obj);
activity.finish();
break;
case R.id.launch_product_query:
Log.d(TAG, "Got product query message");
String url = (String) message.obj;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
activity.startActivity(intent);
break;
}
}
public void quitSynchronously() {
state = State.DONE;
CameraManager.get().stopPreview();
Message quit = Message.obtain(decodeThread.getHandler(), R.id.quit);
quit.sendToTarget();
try {
decodeThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Be absolutely sure we don't send any queued up messages
removeMessages(R.id.decode_succeeded);
removeMessages(R.id.decode_failed);
}
private void restartPreviewAndDecode() {
if (state == State.SUCCESS) {
state = State.PREVIEW;
CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), R.id.decode);
CameraManager.get().requestAutoFocus(this, R.id.auto_focus);
activity.drawViewfinder();
}
}
}
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.decoding;
import android.content.Intent;
import android.net.Uri;
import com.google.zxing.BarcodeFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.regex.Pattern;
final class DecodeFormatManager {
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
static final Vector<BarcodeFormat> PRODUCT_FORMATS;
static final Vector<BarcodeFormat> ONE_D_FORMATS;
static final Vector<BarcodeFormat> QR_CODE_FORMATS;
static final Vector<BarcodeFormat> DATA_MATRIX_FORMATS;
static {
PRODUCT_FORMATS = new Vector<BarcodeFormat>(5);
PRODUCT_FORMATS.add(BarcodeFormat.UPC_A);
PRODUCT_FORMATS.add(BarcodeFormat.UPC_E);
PRODUCT_FORMATS.add(BarcodeFormat.EAN_13);
PRODUCT_FORMATS.add(BarcodeFormat.EAN_8);
PRODUCT_FORMATS.add(BarcodeFormat.RSS_14);
ONE_D_FORMATS = new Vector<BarcodeFormat>(PRODUCT_FORMATS.size() + 4);
ONE_D_FORMATS.addAll(PRODUCT_FORMATS);
ONE_D_FORMATS.add(BarcodeFormat.CODE_39);
ONE_D_FORMATS.add(BarcodeFormat.CODE_93);
ONE_D_FORMATS.add(BarcodeFormat.CODE_128);
ONE_D_FORMATS.add(BarcodeFormat.ITF);
QR_CODE_FORMATS = new Vector<BarcodeFormat>(1);
QR_CODE_FORMATS.add(BarcodeFormat.QR_CODE);
DATA_MATRIX_FORMATS = new Vector<BarcodeFormat>(1);
DATA_MATRIX_FORMATS.add(BarcodeFormat.DATA_MATRIX);
}
private DecodeFormatManager() {
}
static Vector<BarcodeFormat> parseDecodeFormats(Intent intent) {
List<String> scanFormats = null;
String scanFormatsString = intent.getStringExtra(Intents.Scan.SCAN_FORMATS);
if (scanFormatsString != null) {
scanFormats = Arrays.asList(COMMA_PATTERN.split(scanFormatsString));
}
return parseDecodeFormats(scanFormats, intent.getStringExtra(Intents.Scan.MODE));
}
static Vector<BarcodeFormat> parseDecodeFormats(Uri inputUri) {
List<String> formats = inputUri.getQueryParameters(Intents.Scan.SCAN_FORMATS);
if (formats != null && formats.size() == 1 && formats.get(0) != null) {
formats = Arrays.asList(COMMA_PATTERN.split(formats.get(0)));
}
return parseDecodeFormats(formats, inputUri.getQueryParameter(Intents.Scan.MODE));
}
private static Vector<BarcodeFormat> parseDecodeFormats(Iterable<String> scanFormats,
String decodeMode) {
if (scanFormats != null) {
Vector<BarcodeFormat> formats = new Vector<BarcodeFormat>();
try {
for (String format : scanFormats) {
formats.add(BarcodeFormat.valueOf(format));
}
return formats;
} catch (IllegalArgumentException iae) {
// ignore it then
}
}
if (decodeMode != null) {
if (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) {
return PRODUCT_FORMATS;
}
if (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) {
return QR_CODE_FORMATS;
}
if (Intents.Scan.DATA_MATRIX_MODE.equals(decodeMode)) {
return DATA_MATRIX_FORMATS;
}
if (Intents.Scan.ONE_D_MODE.equals(decodeMode)) {
return ONE_D_FORMATS;
}
}
return null;
}
}
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.decoding;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import net.app.zxing.camera.CameraManager;
import net.app.zxing.camera.PlanarYUVLuminanceSource;
import net.codecode.consciencefood.FindScanActivity;
import net.codecode.consciencefood.R;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import java.util.Hashtable;
final class DecodeHandler extends Handler {
private static final String TAG = DecodeHandler.class.getSimpleName();
private final FindScanActivity activity;
private final MultiFormatReader multiFormatReader;
DecodeHandler(FindScanActivity activity, Hashtable<DecodeHintType, Object> hints) {
multiFormatReader = new MultiFormatReader();
multiFormatReader.setHints(hints);
this.activity = activity;
}
@Override
public void handleMessage(Message message) {
switch (message.what) {
case R.id.decode:
// Log.d(TAG, "Got decode message");
decode((byte[]) message.obj, message.arg1, message.arg2);
break;
case R.id.quit:
Looper.myLooper().quit();
break;
}
}
/**
* Decode the data within the viewfinder rectangle, and time how long it
* took. For efficiency, reuse the same reader objects from one decode to
* the next.
*
* @param data The YUV preview frame.
* @param width The width of the preview frame.
* @param height The height of the preview frame.
*/
private void decode(byte[] data, int width, int height) {
long start = System.currentTimeMillis();
Result rawResult = null;
// modify here
byte[] rotatedData = new byte[data.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
rotatedData[x * height + height - y - 1] = data[x + y * width];
}
int tmp = width; // Here we are swapping, that's the difference to #11
width = height;
height = tmp;
PlanarYUVLuminanceSource source = CameraManager.get()
.buildLuminanceSource(rotatedData, width, height);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = multiFormatReader.decodeWithState(bitmap);
} catch (ReaderException re) {
// continue
} finally {
multiFormatReader.reset();
}
if (rawResult != null) {
long end = System.currentTimeMillis();
Log.d(TAG, "Found barcode (" + (end - start) + " ms):\n"
+ rawResult.toString());
Message message = Message.obtain(activity.getHandler(),
R.id.decode_succeeded, rawResult);
Bundle bundle = new Bundle();
bundle.putParcelable(DecodeThread.BARCODE_BITMAP,
source.renderCroppedGreyscaleBitmap());
message.setData(bundle);
// Log.d(TAG, "Sending decode succeeded message...");
message.sendToTarget();
} else {
Message message = Message.obtain(activity.getHandler(), R.id.decode_failed);
message.sendToTarget();
}
}
}
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.decoding;
import android.os.Handler;
import android.os.Looper;
import net.codecode.consciencefood.FindScanActivity;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.ResultPointCallback;
import java.util.Hashtable;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;
/**
* This thread does all the heavy lifting of decoding the images.
*/
final class DecodeThread extends Thread {
public static final String BARCODE_BITMAP = "barcode_bitmap";
private final FindScanActivity activity;
private final Hashtable<DecodeHintType, Object> hints;
private Handler handler;
private final CountDownLatch handlerInitLatch;
DecodeThread(FindScanActivity activity,
Vector<BarcodeFormat> decodeFormats, String characterSet,
ResultPointCallback resultPointCallback) {
this.activity = activity;
handlerInitLatch = new CountDownLatch(1);
hints = new Hashtable<DecodeHintType, Object>(3);
if (decodeFormats == null || decodeFormats.isEmpty()) {
decodeFormats = new Vector<BarcodeFormat>();
decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
}
hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
if (characterSet != null) {
hints.put(DecodeHintType.CHARACTER_SET, characterSet);
}
hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, resultPointCallback);
}
Handler getHandler() {
try {
handlerInitLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return handler;
}
@Override
public void run() {
Looper.prepare();
handler = new DecodeHandler(activity, hints);
handlerInitLatch.countDown();
Looper.loop();
}
}
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.decoding;
import android.app.Activity;
import android.content.DialogInterface;
/**
* Simple listener used to exit the app in a few cases.
*/
public final class FinishListener
implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener, Runnable {
private final Activity activityToFinish;
public FinishListener(Activity activityToFinish) {
this.activityToFinish = activityToFinish;
}
public void onCancel(DialogInterface dialogInterface) {
run();
}
public void onClick(DialogInterface dialogInterface, int i) {
run();
}
public void run() {
activityToFinish.finish();
}
}
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.decoding;
import android.app.Activity;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* Finishes an activity after a period of inactivity.
*/
public final class InactivityTimer {
private static final int INACTIVITY_DELAY_SECONDS = 5 * 60;
private final ScheduledExecutorService inactivityTimer =
Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory());
private final Activity activity;
private ScheduledFuture<?> inactivityFuture = null;
public InactivityTimer(Activity activity) {
this.activity = activity;
onActivity();
}
public void onActivity() {
cancel();
inactivityFuture = inactivityTimer.schedule(new FinishListener(activity),
INACTIVITY_DELAY_SECONDS,
TimeUnit.SECONDS);
}
private void cancel() {
if (inactivityFuture != null) {
inactivityFuture.cancel(true);
inactivityFuture = null;
}
}
public void shutdown() {
cancel();
inactivityTimer.shutdown();
}
private static final class DaemonThreadFactory implements ThreadFactory {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
}
}
}
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.decoding;
/**
* This class provides the constants to use when sending an Intent to Barcode Scanner.
* These strings are effectively API and cannot be changed.
*/
public final class Intents {
private Intents() {
}
public static final class Scan {
/**
* Send this intent to open the Barcodes app in scanning mode, find a barcode, and return
* the results.
*/
public static final String ACTION = "com.google.zxing.client.android.SCAN";
/**
* By default, sending Scan.ACTION will decode all barcodes that we understand. However it
* may be useful to limit scanning to certain formats. Use Intent.putExtra(MODE, value) with
* one of the values below ({@link #PRODUCT_MODE}, {@link #ONE_D_MODE}, {@link #QR_CODE_MODE}).
* Optional.
* <p>
* Setting this is effectively shorthnad for setting explicit formats with {@link #SCAN_FORMATS}.
* It is overridden by that setting.
*/
public static final String MODE = "SCAN_MODE";
/**
* Comma-separated list of formats to scan for. The values must match the names of
* {@link com.google.zxing.BarcodeFormat}s, such as {@link com.google.zxing.BarcodeFormat#EAN_13}.
* Example: "EAN_13,EAN_8,QR_CODE"
* <p>
* This overrides {@link #MODE}.
*/
public static final String SCAN_FORMATS = "SCAN_FORMATS";
/**
* @see com.google.zxing.DecodeHintType#CHARACTER_SET
*/
public static final String CHARACTER_SET = "CHARACTER_SET";
/**
* Decode only UPC and EAN barcodes. This is the right choice for shopping apps which get
* prices, reviews, etc. for products.
*/
public static final String PRODUCT_MODE = "PRODUCT_MODE";
/**
* Decode only 1D barcodes (currently UPC, EAN, Code 39, and Code 128).
*/
public static final String ONE_D_MODE = "ONE_D_MODE";
/**
* Decode only QR codes.
*/
public static final String QR_CODE_MODE = "QR_CODE_MODE";
/**
* Decode only Data Matrix codes.
*/
public static final String DATA_MATRIX_MODE = "DATA_MATRIX_MODE";
/**
* If a barcode is found, Barcodes returns RESULT_OK to onActivityResult() of the app which
* requested the scan via startSubActivity(). The barcodes contents can be retrieved with
* intent.getStringExtra(RESULT). If the user presses Back, the result code will be
* RESULT_CANCELED.
*/
public static final String RESULT = "SCAN_RESULT";
/**
* Call intent.getStringExtra(RESULT_FORMAT) to determine which barcode format was found.
* See Contents.Format for possible values.
*/
public static final String RESULT_FORMAT = "SCAN_RESULT_FORMAT";
/**
* Setting this to false will not save scanned codes in the history.
*/
public static final String SAVE_HISTORY = "SAVE_HISTORY";
private Scan() {
}
}
public static final class Encode {
/**
* Send this intent to encode a piece of data as a QR code and display it full screen, so
* that another person can scan the barcode from your screen.
*/
public static final String ACTION = "com.google.zxing.client.android.ENCODE";
/**
* The data to encode. Use Intent.putExtra(DATA, data) where data is either a String or a
* Bundle, depending on the type and format specified. Non-QR Code formats should
* just use a String here. For QR Code, see Contents for details.
*/
public static final String DATA = "ENCODE_DATA";
/**
* The type of data being supplied if the format is QR Code. Use
* Intent.putExtra(TYPE, type) with one of Contents.Type.
*/
public static final String TYPE = "ENCODE_TYPE";
/**
* The barcode format to be displayed. If this isn't specified or is blank,
* it defaults to QR Code. Use Intent.putExtra(FORMAT, format), where
* format is one of Contents.Format.
*/
public static final String FORMAT = "ENCODE_FORMAT";
private Encode() {
}
}
public static final class SearchBookContents {
/**
* Use Google Book Search to search the contents of the book provided.
*/
public static final String ACTION = "com.google.zxing.client.android.SEARCH_BOOK_CONTENTS";
/**
* The book to search, identified by ISBN number.
*/
public static final String ISBN = "ISBN";
/**
* An optional field which is the text to search for.
*/
public static final String QUERY = "QUERY";
private SearchBookContents() {
}
}
public static final class WifiConnect {
/**
* Internal intent used to trigger connection to a wi-fi network.
*/
public static final String ACTION = "com.google.zxing.client.android.WIFI_CONNECT";
/**
* The network to connect to, all the configuration provided here.
*/
public static final String SSID = "SSID";
/**
* The network to connect to, all the configuration provided here.
*/
public static final String TYPE = "TYPE";
/**
* The network to connect to, all the configuration provided here.
*/
public static final String PASSWORD = "PASSWORD";
private WifiConnect() {
}
}
public static final class Share {
/**
* Give the user a choice of items to encode as a barcode, then render it as a QR Code and
* display onscreen for a friend to scan with their phone.
*/
public static final String ACTION = "com.google.zxing.client.android.SHARE";
private Share() {
}
}
}
package net.app.zxing.decoding;
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.google.zxing.LuminanceSource;
import java.io.FileNotFoundException;
/**
* This class is used to help decode images from files which arrive as RGB data
* from Android bitmaps. It does not support cropping or rotation.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class RGBLuminanceSource extends LuminanceSource {
private final byte[] luminances;
public RGBLuminanceSource(String path) throws FileNotFoundException {
this(loadBitmap(path));
}
public RGBLuminanceSource(Bitmap bitmap) {
super(bitmap.getWidth(), bitmap.getHeight());
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
// In order to measure pure decoding speed, we convert the entire image
// to a greyscale array
// up front, which is the same as the Y channel of the
// YUVLuminanceSource in the real app.
luminances = new byte[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
int pixel = pixels[offset + x];
int r = (pixel >> 16) & 0xff;
int g = (pixel >> 8) & 0xff;
int b = pixel & 0xff;
if (r == g && g == b) {
// Image is already greyscale, so pick any channel.
luminances[offset + x] = (byte) r;
} else {
// Calculate luminance cheaply, favoring green.
luminances[offset + x] = (byte) ((r + g + g + b) >> 2);
}
}
}
}
@Override
public byte[] getRow(int y, byte[] row) {
if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException(
"Requested row is outside the image: " + y);
}
int width = getWidth();
if (row == null || row.length < width) {
row = new byte[width];
}
System.arraycopy(luminances, y * width, row, 0, width);
return row;
}
// Since this class does not support cropping, the underlying byte array
// already contains
// exactly what the caller is asking for, so give it to them without a copy.
@Override
public byte[] getMatrix() {
return luminances;
}
private static Bitmap loadBitmap(String path) throws FileNotFoundException {
Bitmap bitmap = BitmapFactory.decodeFile(path);
if (bitmap == null) {
throw new FileNotFoundException("Couldn't open " + path);
}
return bitmap;
}
}
\ No newline at end of file
/*
* Copyright (C) 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.view;
import com.google.zxing.ResultPoint;
import com.google.zxing.ResultPointCallback;
public final class ViewfinderResultPointCallback implements ResultPointCallback {
private final ViewfinderView viewfinderView;
public ViewfinderResultPointCallback(ViewfinderView viewfinderView) {
this.viewfinderView = viewfinderView;
}
public void foundPossibleResultPoint(ResultPoint point) {
viewfinderView.addPossibleResultPoint(point);
}
}
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.app.zxing.view;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import net.app.zxing.camera.CameraManager;
import net.codecode.consciencefood.R;
import com.google.zxing.ResultPoint;
import java.util.Collection;
import java.util.HashSet;
/**
* This view is overlaid on top of the camera preview. It adds the viewfinder
* rectangle and partial transparency outside it, as well as the laser scanner
* animation and result points.
*/
public final class ViewfinderView extends View {
/**
* 刷新界面的时间
*/
private static final long ANIMATION_DELAY = 10L;
private static final int OPAQUE = 0xFF;
/**
* 四个绿色边角对应的长度
*/
private int ScreenRate;
/**
* 四个绿色边角对应的宽度
*/
private static final int CORNER_WIDTH = 10;
/**
* 扫描框中的中间线的宽度
*/
private static final int MIDDLE_LINE_WIDTH = 6;
/**
* 扫描框中的中间线的与扫描框左右的间隙
*/
private static final int MIDDLE_LINE_PADDING = 5;
/**
* 中间那条线每次刷新移动的距离
*/
private static final int SPEEN_DISTANCE = 5;
/**
* 手机的屏幕密度
*/
private static float density;
/**
* 字体大小
*/
private static final int TEXT_SIZE = 16;
/**
* 字体距离扫描框下面的距离
*/
private static final int TEXT_PADDING_TOP = 30;
/**
* 画笔对象的引用
*/
private Paint paint;
/**
* 中间滑动线的最顶端位置
*/
private int slideTop;
/**
* 中间滑动线的最底端位置
*/
@SuppressWarnings("unused")
private int slideBottom;
/**
* 将扫描的二维码拍下来,这里没有这个功能,暂时不考虑
*/
private Bitmap resultBitmap;
private final int maskColor;
private final int resultColor;
private final int resultPointColor;
private Collection<ResultPoint> possibleResultPoints;
private Collection<ResultPoint> lastPossibleResultPoints;
boolean isFirst;
public ViewfinderView(Context context, AttributeSet attrs) {
super(context, attrs);
density = context.getResources().getDisplayMetrics().density;
//将像素转换成dp
ScreenRate = (int) (20 * density);
paint = new Paint();
Resources resources = getResources();
maskColor = resources.getColor(R.color.viewfinder_mask);
resultColor = resources.getColor(R.color.result_view);
resultPointColor = resources.getColor(R.color.possible_result_points);
possibleResultPoints = new HashSet<ResultPoint>(5);
}
@Override
public void onDraw(Canvas canvas) {
//中间的扫描框,你要修改扫描框的大小,去CameraManager里面修改
Rect frame = CameraManager.get().getFramingRect();
if (frame == null) {
return;
}
//初始化中间线滑动的最上边和最下边
if (!isFirst) {
isFirst = true;
slideTop = frame.top;
slideBottom = frame.bottom;
}
//获取屏幕的宽和高
int width = canvas.getWidth();
int height = canvas.getHeight();
paint.setColor(resultBitmap != null ? resultColor : maskColor);
//画出扫描框外面的阴影部分,共四个部分,扫描框的上面到屏幕上面,扫描框的下面到屏幕下面
//扫描框的左边面到屏幕左边,扫描框的右边到屏幕右边
canvas.drawRect(0, 0, width, frame.top, paint);
canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1,
paint);
canvas.drawRect(0, frame.bottom + 1, width, height, paint);
if (resultBitmap != null) {
// Draw the opaque result bitmap over the scanning rectangle
paint.setAlpha(OPAQUE);
canvas.drawBitmap(resultBitmap, frame.left, frame.top, paint);
} else {
//画扫描框边上的角,总共8个部分
paint.setColor(Color.GREEN);
canvas.drawRect(frame.left, frame.top, frame.left + ScreenRate,
frame.top + CORNER_WIDTH, paint);
canvas.drawRect(frame.left, frame.top, frame.left + CORNER_WIDTH, frame.top
+ ScreenRate, paint);
canvas.drawRect(frame.right - ScreenRate, frame.top, frame.right,
frame.top + CORNER_WIDTH, paint);
canvas.drawRect(frame.right - CORNER_WIDTH, frame.top, frame.right, frame.top
+ ScreenRate, paint);
canvas.drawRect(frame.left, frame.bottom - CORNER_WIDTH, frame.left
+ ScreenRate, frame.bottom, paint);
canvas.drawRect(frame.left, frame.bottom - ScreenRate,
frame.left + CORNER_WIDTH, frame.bottom, paint);
canvas.drawRect(frame.right - ScreenRate, frame.bottom - CORNER_WIDTH,
frame.right, frame.bottom, paint);
canvas.drawRect(frame.right - CORNER_WIDTH, frame.bottom - ScreenRate,
frame.right, frame.bottom, paint);
//绘制中间的线,每次刷新界面,中间的线往下移动SPEEN_DISTANCE
slideTop += SPEEN_DISTANCE;
if (slideTop >= frame.bottom) {
slideTop = frame.top;
}
canvas.drawRect(frame.left + MIDDLE_LINE_PADDING, slideTop - MIDDLE_LINE_WIDTH / 2, frame.right - MIDDLE_LINE_PADDING, slideTop + MIDDLE_LINE_WIDTH / 2, paint);
//画扫描框下面的字
paint.setColor(Color.WHITE);
paint.setTextSize(TEXT_SIZE * density);
paint.setAlpha(0x40);
paint.setTypeface(Typeface.create("System", Typeface.BOLD));
canvas.drawText(getResources().getString(R.string.scan_text), frame.left, (float) (frame.bottom + (float) TEXT_PADDING_TOP * density), paint);
Collection<ResultPoint> currentPossible = possibleResultPoints;
Collection<ResultPoint> currentLast = lastPossibleResultPoints;
if (currentPossible.isEmpty()) {
lastPossibleResultPoints = null;
} else {
possibleResultPoints = new HashSet<ResultPoint>(5);
lastPossibleResultPoints = currentPossible;
paint.setAlpha(OPAQUE);
paint.setColor(resultPointColor);
for (ResultPoint point : currentPossible) {
canvas.drawCircle(frame.left + point.getX(), frame.top
+ point.getY(), 6.0f, paint);
}
}
if (currentLast != null) {
paint.setAlpha(OPAQUE / 2);
paint.setColor(resultPointColor);
for (ResultPoint point : currentLast) {
canvas.drawCircle(frame.left + point.getX(), frame.top
+ point.getY(), 3.0f, paint);
}
}
//只刷新扫描框的内容,其他地方不刷新
postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top,
frame.right, frame.bottom);
}
}
public void drawViewfinder() {
resultBitmap = null;
invalidate();
}
/**
* Draw a bitmap with the result points highlighted instead of the live
* scanning display.
*
* @param barcode An image of the decoded barcode.
*/
public void drawResultBitmap(Bitmap barcode) {
resultBitmap = barcode;
invalidate();
}
public void addPossibleResultPoint(ResultPoint point) {
possibleResultPoints.add(point);
}
}
package net.codecode.consciencefood;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
/**
* Created by shx and 2020/9/4.
*/
public class DBOpenHelper extends SQLiteOpenHelper {
public DBOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String create_table = "create table if not exists collection_imf(_id integer primary key autoincrement, name text, date text, comment text, image BLOB)";
sqLiteDatabase.execSQL(create_table);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
package net.codecode.consciencefood;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import net.app.zxing.camera.CameraManager;
import net.app.zxing.decoding.CaptureActivityHandler;
import net.app.zxing.decoding.InactivityTimer;
import net.app.zxing.decoding.RGBLuminanceSource;
import net.app.zxing.view.ViewfinderView;
import net.codecode.consciencefood.util.BitmapUtil;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import java.io.IOException;
import java.util.Hashtable;
/**
* Created by ouyangshen on 2017/11/4.
*/
@SuppressLint("DefaultLocale")
public class FindScanActivity extends Activity implements SurfaceHolder.Callback {
private static final int REQUEST_CODE_SCAN_GALLERY = 100;
private final static String TAG = "FindScanActivity";
private CaptureActivityHandler mHandler;
private ViewfinderView vv_finder; // 定义一个扫码视图对象
private boolean hasSurface = false; // 是否创建了渲染表面
private InactivityTimer mTimer;
private MediaPlayer mPlayer; // 声明一个媒体播放器对象
private boolean hasBeep; // 是否支持响铃
private ImageButton back;
private Button btnAlbum; // 相册
private ProgressDialog mProgress;
private Bitmap scanBitmap;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_scan);
CameraManager.init(getApplication(), CameraManager.QR_CODE);
// 从布局文件中获取名叫vv_finder的扫码视图
vv_finder = findViewById(R.id.vv_finder);
mTimer = new InactivityTimer(this);
back = (ImageButton) findViewById(R.id.btn_back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
btnAlbum = (Button) findViewById(R.id.btn_album);
btnAlbum.setOnClickListener(albumOnClick);
}
private View.OnClickListener albumOnClick = new View.OnClickListener() {
@Override
public void onClick(View view) {
//打开手机中的相册
Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); //"android.intent.action.GET_CONTENT"
innerIntent.setType("image/*");
startActivityForResult(innerIntent, REQUEST_CODE_SCAN_GALLERY);
}
};
@Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
if (resultCode==RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_SCAN_GALLERY:
handleAlbumPic(data);
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* 处理选择的图片
* @param data
*/
private void handleAlbumPic(Intent data) {
//获取选中图片的路径
final Uri uri = data.getData();
mProgress = new ProgressDialog(FindScanActivity.this);
mProgress.setMessage("正在扫描...");
mProgress.setCancelable(false);
mProgress.show();
runOnUiThread(new Runnable() {
@Override
public void run() {
Result result = scanningImage(uri);
mProgress.dismiss();
if (result != null) {
Intent intent = new Intent(FindScanActivity.this, ScanResultActivity.class);
intent.putExtra("result", result.getText());
startActivity(intent);
} else {
Toast.makeText(FindScanActivity.this, "识别失败", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* 扫描二维码图片的方法
* @param uri
* @return
*/
public Result scanningImage(Uri uri) {
if (uri == null) {
return null;
}
Hashtable<DecodeHintType, String> hints = new Hashtable<>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码
scanBitmap = BitmapUtil.decodeUri(this, uri, 500, 500);
RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
try {
return reader.decode(bitmap1, hints);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (ChecksumException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onResume() {
super.onResume();
// 从布局文件中获取名叫sv_scan的表面视图
SurfaceView sv_scan = findViewById(R.id.sv_scan);
// 从表面视图获取表面持有者
SurfaceHolder surfaceHolder = sv_scan.getHolder();
if (hasSurface) { // 已创建渲染表面
initCamera(surfaceHolder);
} else { // 未创建渲染表面
surfaceHolder.addCallback(this);
}
hasBeep = true;
// 从系统服务中获取音频管理器
AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
hasBeep = false;
}
initBeepSound();
}
@Override
protected void onPause() {
super.onPause();
if (mHandler != null) {
mHandler.quitSynchronously();
mHandler = null;
}
CameraManager.get().closeDriver();
}
@Override
protected void onDestroy() {
mTimer.shutdown();
super.onDestroy();
}
public void handleDecode(Result result, Bitmap barcode) {
mTimer.onActivity();
beepAndVibrate();
// 读取二维码分析后的结果字符串
String resultString = result.getText();
if (resultString == null || resultString.length() <= 0) {
Toast.makeText(this, "Scan failed or result is null", Toast.LENGTH_SHORT).show();
} else {
String desc = String.format("barcode width=%d,height=%d",
barcode.getWidth(), barcode.getHeight());
Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
// 跳到扫描结果页面
Intent intent = new Intent(this, ScanResultActivity.class);
intent.putExtra("result", resultString);
startActivity(intent);
}
}
// 初始化相机
private void initCamera(SurfaceHolder surfaceHolder) {
try {
CameraManager.get().openDriver(surfaceHolder);
if (mHandler == null) {
mHandler = new CaptureActivityHandler(this, null, null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 在渲染表面变更时触发
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
// 在渲染表面创建时触发
public void surfaceCreated(SurfaceHolder holder) {
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
// 在渲染表面销毁时触发
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
public ViewfinderView getViewfinderView() {
return vv_finder;
}
public Handler getHandler() {
return mHandler;
}
public void drawViewfinder() {
vv_finder.drawViewfinder();
}
// 初始化哔哔音效
private void initBeepSound() {
if (hasBeep && mPlayer == null) {
// 设置当前页面的音频流类型
setVolumeControlStream(AudioManager.STREAM_MUSIC);
// 创建一个媒体播放器
mPlayer = new MediaPlayer();
// 设置媒体播放器的音频流类型
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// 设置媒体播放器的播放结束监听器
mPlayer.setOnCompletionListener(beepListener);
AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
try {
// 设置媒体播放器的媒体数据来源
mPlayer.setDataSource(file.getFileDescriptor(),
file.getStartOffset(), file.getLength());
file.close();
// 设置媒体播放器的左右声道音量
mPlayer.setVolume(0.1f, 0.1f);
// 执行媒体播放器的准备动作
mPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
mPlayer = null;
}
}
}
private static final long VIBRATE_DURATION = 200L; // 震动时长
private void beepAndVibrate() {
if (hasBeep && mPlayer != null) {
// 媒体播放器开始播放音频
mPlayer.start();
}
// 从系统服务中获取震动器
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
// 命令震动器震动若干秒
vibrator.vibrate(VIBRATE_DURATION);
}
// 定义一个播放结束监听器。一旦音频播放完毕,就触发监听器的onCompletion方法
private final OnCompletionListener beepListener = new OnCompletionListener() {
public void onCompletion(MediaPlayer mPlayer) {
// 把媒体播放器的播放进度拖到最开始,即0秒处
mPlayer.seekTo(0);
}
};
}
\ No newline at end of file
package net.codecode.consciencefood;
/**
* Created by shx and 2020/9/14.
*/
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import net.codecode.consciencefood.util.DateUtil;
import net.codecode.consciencefood.util.SwitchUtil;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by ouyangshen on 2017/11/4.
*/
@SuppressLint(value={"DefaultLocale","SetTextI18n"})
public class LocationActivity extends AppCompatActivity {
private final static String TAG = "LocationActivity";
private TextView tv_location;
private String mLocation = "";
private LocationManager mLocationMgr; // 声明一个定位管理器对象
private Criteria mCriteria = new Criteria(); // 声明一个定位准则对象
private Handler mHandler = new Handler(); // 声明一个处理器
private boolean isLocationEnable = false; // 定位服务是否可用
ListView list;
ArrayList arraylist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
tv_location = findViewById(R.id.tv_location);
list = (ListView)findViewById(R.id.list);
SwitchUtil.checkGpsIsOpen(this, "需要打开定位功能才能查看定位结果信息");
}
@Override
protected void onResume() {
super.onResume();
mHandler.removeCallbacks(mRefresh); // 移除定位刷新任务
initLocation();
mHandler.postDelayed(mRefresh, 100); // 延迟100毫秒启动定位刷新任务
}
// 初始化定位服务
private void initLocation() {
// 从系统服务中获取定位管理器
mLocationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 设置定位精确度。Criteria.ACCURACY_COARSE表示粗略,Criteria.ACCURACY_FIN表示精细
mCriteria.setAccuracy(Criteria.ACCURACY_FINE);
// 设置是否需要海拔信息
mCriteria.setAltitudeRequired(true);
// 设置是否需要方位信息
mCriteria.setBearingRequired(true);
// 设置是否允许运营商收费
mCriteria.setCostAllowed(true);
// 设置对电源的需求
mCriteria.setPowerRequirement(Criteria.POWER_LOW);
// 获取定位管理器的最佳定位提供者
String bestProvider = mLocationMgr.getBestProvider(mCriteria, true);
if (mLocationMgr.isProviderEnabled(bestProvider)) { // 定位提供者当前可用
tv_location.setText("正在获取" + bestProvider + "定位对象");
mLocation = String.format("定位类型=%s", bestProvider);
beginLocation(bestProvider);
isLocationEnable = true;
} else { // 定位提供者暂不可用
tv_location.setText("\n" + bestProvider + "定位不可用");
isLocationEnable = false;
}
}
public static String convertToSexagesimal(Double num){
int du=(int)Math.floor(Math.abs(num)); //获取整数部分
double temp=getdPoint(Math.abs(num))*60;
int fen=(int)Math.floor(temp); //获取整数部分
temp =getdPoint(temp)*60;
int miao=(int)Math.floor(temp);
return du+"°"+fen+"'"+miao+"\"";
}
//获取小数部分
private static double getdPoint(double num){
double d = num;
int fInt = (int) d;
BigDecimal b1 = new BigDecimal(Double.toString(d));
BigDecimal b2 = new BigDecimal(Integer.toString(fInt));
double dPoint = b1.subtract(b2).floatValue();
return dPoint;
}
// 设置定位结果文本
private void setLocationText(Location location) {
if (location != null) {
arraylist = new ArrayList();
HashMap map = new HashMap();
String preLatiStr = location.getLatitude() > 0 ? "北纬:" : "南纬:";
String preLongiStr = location.getLongitude() > 0 ? "东经:" : "西经:";
map.put("longitude", preLongiStr + convertToSexagesimal(location.getLongitude()));
map.put("latitude", preLatiStr + convertToSexagesimal(location.getLatitude()));
map.put("altitude", location.getAltitude() + "m");
map.put("accuracy", location.getAccuracy() + "m");
arraylist.add(map);
SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), arraylist,
R.layout.location_item, new String[]{"longitude", "latitude", "altitude", "accuracy"},
new int[]{R.id.longitude_value, R.id.latitude_value, R.id.altitude_value, R.id.accuracy_value});
list.setAdapter(adapter);
tv_location.setVisibility(View.GONE);
} else {
tv_location.setText(mLocation + "\n暂未获取到定位对象");
}
}
// 开始定位
private void beginLocation(String method) {
// 检查当前设备是否已经开启了定位功能
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "请授予定位权限并开启定位功能", Toast.LENGTH_SHORT).show();
return;
}
// 设置定位管理器的位置变更监听器
mLocationMgr.requestLocationUpdates(method, 300, 0, mLocationListener);
// 获取最后一次成功定位的位置信息
Location location = mLocationMgr.getLastKnownLocation(method);
setLocationText(location);
}
// 定义一个位置变更监听器
private LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
setLocationText(location);
}
@Override
public void onProviderDisabled(String arg0) {}
@Override
public void onProviderEnabled(String arg0) {}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
};
// 定义一个刷新任务,若无法定位则每隔一秒就尝试定位
private Runnable mRefresh = new Runnable() {
@Override
public void run() {
if (!isLocationEnable) {
initLocation();
mHandler.postDelayed(this, 1000);
}
}
};
@Override
protected void onDestroy() {
if (mLocationMgr != null) {
// 移除定位管理器的位置变更监听器
mLocationMgr.removeUpdates(mLocationListener);
}
super.onDestroy();
}
}
package net.codecode.consciencefood;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import static android.provider.ContactsContract.CommonDataKinds.Website.URL;
public class LoginActivity extends AppCompatActivity {
EditText ETusername, ETpassword;
Button loginup;
ProgressDialog dialog;
private Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
case 1:
dialog.dismiss();
String answer = msg.obj.toString().trim();
String user = jsonParse(answer);
if (user != null) {
save(ETusername.getText().toString());
Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
finish();
}
break;
case 2:
dialog.dismiss();
Toast.makeText(getApplicationContext(), "网络异常,请重新连接", Toast.LENGTH_SHORT).show();
break;
case 3:
dialog.dismiss();
Toast.makeText(getApplicationContext(), "出现不明异常,让我理一理", Toast.LENGTH_SHORT).show();
break;
case 4:
dialog.dismiss();
Toast.makeText(getApplicationContext(), "系统繁忙请稍后再试", Toast.LENGTH_SHORT).show();
break;
case 5:
dialog.dismiss();
Toast.makeText(getApplicationContext(), "用户不存在或密码错误", Toast.LENGTH_SHORT).show();
break;
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initView();
findViewById(R.id.close_login).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
public String jsonParse(String jsonStr) {
String user = "";
try {
JSONObject jsonObject = new JSONObject(jsonStr);
user = jsonObject.getString("access_token");
} catch (JSONException e) {
e.printStackTrace();
}
return user;
}
private void initView() {
ETusername = (EditText)findViewById(R.id.Login_editUsername);
ETpassword = (EditText)findViewById(R.id.Login_editPassword);
loginup = (Button)findViewById(R.id.Login_btnLoginup);
loginup.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
String username = ETusername.getText().toString();
String password = ETpassword.getText().toString();
if (username.length() != 0 && password.length() != 0) {
dialog = new ProgressDialog(LoginActivity.this);
dialog.setTitle("提示");
dialog.setMessage("正在登录,请稍后...");
dialog.setCancelable(false);
dialog.show();
LoginThread(username, password);
}
else {
Toast.makeText(LoginActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
}
}
});
}
private void LoginThread(final String username, final String password) {
Thread login = new Thread(new Runnable() {
@Override
public void run() {
LoginHttp(username, password);
}
});
login.start();
}
public void save(String username) {
SharedPreferences sp = this.getSharedPreferences("user_info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("username", username);
editor.commit();
}
private void LoginHttp(String username, String password) {
HttpsURLConnection conn = null;
InputStream is = null;
// DataOutputStream out = null;
try {
String path = "https://www.codecode.net/oauth/token/";
URL url = new URL(path);
// path = path + "?grant_type=password" + "&username="+username+"&passwrod="+password;
conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// conn.connect();
String grant_type = "password";
String params = "{" +
"\"grant_type\":\"" + grant_type + "\"" + "," +
"\"username\":\"" + username + "\"" + "," +
"\"password\":\"" + password + "\"" +
"}";
OutputStream out = conn.getOutputStream();
out.write(params.getBytes());
out.flush();
out.close();
int retCode = conn.getResponseCode();
if (retCode == 200) {
is = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
StringBuilder sb = new StringBuilder();
while((len = is.read(buffer)) != -1) {
is.read(buffer);
String data = new String(buffer);
sb.append(data);
}
String response = sb.toString();
Message msg = new Message();
msg.what = 1;
msg.obj = response;
handler.sendMessage(msg);
}
else if(retCode == 401) {
handler.sendEmptyMessage(5);
}
} catch (MalformedURLException e) {
handler.sendEmptyMessage(2);
e.printStackTrace();
} catch (Exception e) {
handler.sendEmptyMessage(3);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
\ No newline at end of file
package net.codecode.consciencefood;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.Manifest;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import net.codecode.consciencefood.fragment.Gourmet_gragment;
import net.codecode.consciencefood.fragment.Home_fragment;
import net.codecode.consciencefood.fragment.Order_Fragment;
import net.codecode.consciencefood.fragment.PersonalCenter;
import net.codecode.consciencefood.util.PermissionUtil;
public class MainActivity extends AppCompatActivity {
private RadioGroup myradioGroup;
private RadioButton rbutton1, rbutton2, rbutton3, rbutton4;
private Resources res;
private Drawable icon_home_true, icon_home_false, icon_me_false, icon_me_true,
icon_community_true, icon_community_false, icon_order_true, icon_order_false;
private int fontColor_false, fontColor_true;
private FragmentManager fgm;
private void initView() {
myradioGroup = (RadioGroup)findViewById(R.id.main_radioGroup);
rbutton1 = (RadioButton)findViewById(R.id.main_radio0);
rbutton2 = (RadioButton)findViewById(R.id.main_radio1);
rbutton3 = (RadioButton)findViewById(R.id.main_radio2);
rbutton4 = (RadioButton)findViewById(R.id.main_radio3);
// findViewById(R.id.btn_location_begin).setOnClickListener(new View.OnClickListener(){
// @Override
// public void onClick(View v) {
// if (PermissionUtil.checkPermission(getParent(), Manifest.permission.ACCESS_FINE_LOCATION, R.id.btn_location_begin % 4096)) {
// PermissionUtil.goActivity(getApplicationContext(), LocationActivity.class);
// }
// }
// });
res = getResources();
icon_home_true = res.getDrawable(R.mipmap.icon_home_true);
icon_home_false = res.getDrawable(R.mipmap.icon_home_false);
icon_community_true = res.getDrawable(R.mipmap.icon_community_true);
icon_community_false = res.getDrawable(R.mipmap.icon_community_false);
icon_order_true = res.getDrawable(R.mipmap.icon_order_true);
icon_order_false = res.getDrawable(R.mipmap.icon_order_false);
icon_me_true = res.getDrawable(R.mipmap.icon_me_true);
icon_me_false = res.getDrawable(R.mipmap.icon_me_false);
fontColor_false = res.getColor(R.color.navigation_false);
fontColor_true = res.getColor(R.color.public_green);
}
private void setAllColor() {
rbutton1.setTextColor(fontColor_false);
rbutton2.setTextColor(fontColor_false);
rbutton3.setTextColor(fontColor_false);
rbutton4.setTextColor(fontColor_false);
}
private void setAllImage() {
rbutton1.setCompoundDrawablesWithIntrinsicBounds(null, icon_home_false,null, null);
rbutton2.setCompoundDrawablesWithIntrinsicBounds(null, icon_community_false,null, null);
rbutton3.setCompoundDrawablesWithIntrinsicBounds(null, icon_order_false,null, null);
rbutton4.setCompoundDrawablesWithIntrinsicBounds(null, icon_me_false,null, null);
}
private void navigation() {
myradioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
setAllColor();
setAllImage();
FragmentTransaction trasaction = fgm.beginTransaction();
switch (i) {
case R.id.main_radio0:
rbutton1.setTextColor(fontColor_true);
rbutton1.setCompoundDrawablesWithIntrinsicBounds(null, icon_home_true, null, null);
trasaction.replace(R.id.main_framelayout, new Home_fragment());
// Toast.makeText(MainActivity.this,"首页", Toast.LENGTH_SHORT).show();
break;
case R.id.main_radio1:
rbutton2.setTextColor(fontColor_true);
rbutton2.setCompoundDrawablesWithIntrinsicBounds(null, icon_community_true, null, null);
trasaction.replace(R.id.main_framelayout, new Gourmet_gragment());
// Toast.makeText(MainActivity.this,"吃货驾到", Toast.LENGTH_SHORT).show();
break;
case R.id.main_radio2:
rbutton3.setTextColor(fontColor_true);
rbutton3.setCompoundDrawablesWithIntrinsicBounds(null, icon_order_true, null, null);
trasaction.replace(R.id.main_framelayout, new Order_Fragment());
// Toast.makeText(MainActivity.this,"我的订单", Toast.LENGTH_SHORT).show();
break;
case R.id.main_radio3:
rbutton4.setTextColor(fontColor_true);
rbutton4.setCompoundDrawablesWithIntrinsicBounds(null, icon_me_true, null, null);
trasaction.replace(R.id.main_framelayout, new PersonalCenter());
// Toast.makeText(MainActivity.this,"个人中心", Toast.LENGTH_SHORT).show();
break;
}
trasaction.commit();
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fgm = this.getSupportFragmentManager();
initView();
showHome();
navigation();
// Button btn = (Button) findViewById(R.id.btntoast);
// btn.setOnClickListener(new View.OnClickListener(){
//
// @Override
// public void onClick(View v) {
//// Toast.makeText(this, "testtoast", Toast.LENGTH_LONG).show();
//// Toast.makeText(this, "testtoast", Toast.LENGTH_LONG).show();
// }
// });
}
private void showHome() {
FragmentTransaction trasaction = fgm.beginTransaction();
trasaction.replace(R.id.main_framelayout, new Home_fragment());
trasaction.commit();
}
}
\ No newline at end of file
package net.codecode.consciencefood;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import net.codecode.consciencefood.util.PermissionUtil;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
/**
* Created by shx and 2020/9/14.
*/
public class MoreActivity extends AppCompatActivity implements View.OnClickListener{
public static Activity act;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_more);
findViewById(R.id.positiondetail).setOnClickListener(this);
findViewById(R.id.scandetail).setOnClickListener(this);
findViewById(R.id.weatherdetail).setOnClickListener(this);
findViewById(R.id.imageView1).setOnClickListener(this);
findViewById(R.id.imageView2).setOnClickListener(this);
findViewById(R.id.imageView3).setOnClickListener(this);
findViewById(R.id.textView1).setOnClickListener(this);
findViewById(R.id.textView2).setOnClickListener(this);
findViewById(R.id.textView3).setOnClickListener(this);
act = this;
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.positiondetail
|| v.getId() == R.id.textView2
|| v.getId() == R.id.imageView2) {
if (PermissionUtil.checkPermission(this, Manifest.permission.ACCESS_FINE_LOCATION, R.id.positiondetail % 4096)) {
PermissionUtil.goActivity(this, LocationActivity.class);
}
} else if (v.getId() == R.id.scandetail
|| v.getId() == R.id.textView3
|| v.getId() == R.id.imageView3) {
// WeFindActivity内嵌到WeChatActivity中,造成不会在底部弹出权限选择对话框,所以要通过WeChatActivity弹窗
// 并且权限选择结果onRequestPermissionsResult要在WeChatActivity里面重写
if (PermissionUtil.checkPermission(MoreActivity.act, Manifest.permission.CAMERA, R.id.scandetail%4096)) {
// 若已获得相机权限,就跳到扫描二维码页面
PermissionUtil.goActivity(this, FindScanActivity.class);
}
} else if (v.getId() == R.id.weatherdetail
|| v.getId() == R.id.textView1
|| v.getId() == R.id.imageView1) {
Intent it = new Intent(MoreActivity.this, WeatherForecastActivity.class);
startActivity(it);
}
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == R.id.scandetail % 4096) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
PermissionUtil.goActivity(this, FindScanActivity.class);
} else {
Toast.makeText(this, "需要允许相机权限才能使用扫一扫噢", Toast.LENGTH_SHORT).show();
}
}
}
}
package net.codecode.consciencefood;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
/**
* Created by ouyangshen on 2017/11/4.
*/
@SuppressLint("SetTextI18n")
public class ScanResultActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_result);
TextView tv_result = findViewById(R.id.tv_result);
// 获取扫码页面传来的结果字符串
String result = getIntent().getStringExtra("result");
tv_result.setText("扫码结果为:" + result);
}
}
package net.codecode.consciencefood;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by shx and 2020/9/3.
*/
public class ViewHolder {
public TextView comment;
public ImageView image;
public TextView date;
public TextView name;
public ImageView praise;
public TextView praise_count;
}
package net.codecode.consciencefood;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import javax.net.ssl.HttpsURLConnection;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
/**
* Created by shx and 2020/9/14.
*/
public class WeatherForecastActivity extends AppCompatActivity {
ListView list;
ArrayList arraylist;
private Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
case 1:
String answer = msg.obj.toString().trim();
jsonParser(answer, "list");
SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), arraylist,
R.layout.weather_item, new String[]{"city", "tem1", "tem2", "wea", "win", "visibility", "air_pm25", "air_level"},
new int[]{R.id.cityValue, R.id.highest_temperature_value, R.id.lowest_temperature_value, R.id.wea_value,
R.id.win_value, R.id.visibility_value, R.id.pm25_value, R.id.air_level_value});
list.setAdapter(adapter);
break;
case 2:
Toast.makeText(getApplicationContext(), "网络异常,请重新连接", Toast.LENGTH_LONG).show();
break;
case 3:
Toast.makeText(getApplicationContext(), "出现不明异常,请待会再试", Toast.LENGTH_LONG).show();
break;
case 4:
Toast.makeText(getApplicationContext(), "json解析不成功", Toast.LENGTH_LONG).show();
break;
}
super.handleMessage(msg);
}
};
private void jsonParser(String jsonStr, String list) {
try {
arraylist = new ArrayList();
JSONObject obj = new JSONObject(jsonStr);
String city = obj.getString("city");
String tem1 = obj.getString("tem1");
String tem2 = obj.getString("tem2");
String wea = obj.getString("wea");
String win = obj.getString("win");
String visibility = obj.getString("visibility");
String air_pm25 = obj.getString("air_pm25");
String air_level = obj.getString("air_level");
HashMap map = new HashMap();
map.put("city", city);
map.put("tem1", tem1);
map.put("tem2", tem2);
map.put("wea", wea);
map.put("win", win);
map.put("visibility", visibility);
map.put("air_pm25", air_pm25);
map.put("air_level", air_level);
arraylist.add(map);
} catch (JSONException e) {
handler.sendEmptyMessage(4);
e.printStackTrace();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
list = (ListView)findViewById(R.id.list);
Thread login = new Thread(new Runnable() {
@Override
public void run() {
LoginHttpServlet();
}
});
login.start();
}
private void LoginHttpServlet() {
HttpsURLConnection conn = null;
InputStream is = null;
try {
String path = "https://tianqiapi.com/api?version=v6&appid=61227349&appsecret=wXQ8jccL&city=北京";
URL url = new URL(path);
conn = (HttpsURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
int retCode = conn.getResponseCode();
if (retCode == 200) {
is = conn.getInputStream();
byte[] buffer = new byte[2056];
int len = 0;
StringBuilder sb = new StringBuilder();
while ((len = is.read(buffer)) != -1) {
is.read(buffer);
String data = new String(buffer);
sb.append(data);
}
String response = sb.toString();
Message msg = new Message();
msg.what = 1;
msg.obj = response;
handler.sendMessage(msg);
}
} catch (MalformedURLException e) {
handler.sendEmptyMessage(2);
e.printStackTrace();
} catch (Exception e) {
handler.sendEmptyMessage(3);
e.printStackTrace();
} finally {
if(conn != null) {
conn.disconnect();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package net.codecode.consciencefood.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import net.codecode.consciencefood.R;
import net.codecode.consciencefood.ViewHolder;
import java.util.HashMap;
import java.util.List;
/**
* Created by shx and 2020/9/3.
*/
public class GourmetBaseAdapter extends BaseAdapter {
List<HashMap> data;
Context mContext = null;
ViewHolder viewHolder = null;
int count[];
public GourmetBaseAdapter(List<HashMap> mydata, Context myContext) {
data = mydata;
mContext = myContext;
count = new int[mydata.size()];
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater mInflater = LayoutInflater.from(mContext);
convertView = mInflater.inflate(R.layout.buju_gourmet_listview, null);
viewHolder.name = (TextView)convertView.findViewById(R.id.buju_gourment_username);
viewHolder.date = (TextView)convertView.findViewById(R.id.buju_goument_time);
viewHolder.comment = (TextView)convertView.findViewById(R.id.buju_gourment_text);
viewHolder.image = (ImageView)convertView.findViewById(R.id.buju_gourment_pic);
viewHolder.praise = (ImageView)convertView.findViewById(R.id.buju_goument_praise);
viewHolder.praise_count = (TextView)convertView.findViewById(R.id.buju_gourment_count);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.name.setText(data.get(i).get("name").toString());
viewHolder.date.setText(data.get(i).get("date").toString());
viewHolder.comment.setText(data.get(i).get("comment").toString());
viewHolder.image.setBackgroundResource((Integer)data.get(i).get("image"));
viewHolder.praise_count.setText(count[i]+"");
viewHolder.praise.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
count[i] = count[i] + 1;
GourmetBaseAdapter.this.notifyDataSetChanged();
}
});
return convertView;
}
}
package net.codecode.consciencefood.adapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
/**
* Created by shx and 2020/9/2.
*/
public class HomeVpAdapter extends PagerAdapter {
List<ImageView> mImages;
public HomeVpAdapter(List<ImageView> images) {
this.mImages = images;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
container.addView(mImages.get(position));
return mImages.get(position);
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View)object);
}
@Override
public int getCount() {
return mImages.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
}
package net.codecode.consciencefood.adapter;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import net.codecode.consciencefood.R;
import net.codecode.consciencefood.ViewHolder;
import java.util.HashMap;
import java.util.List;
/**
* Created by shx and 2020/9/4.
*/
public class OrderBaseAdapter extends BaseAdapter {
List<HashMap<String, Object>> data;
Context mcontext;
ViewHolder viewHolder = null;
public OrderBaseAdapter(List<HashMap<String, Object>> mydata, Context myContext) {
data = mydata;
mcontext = myContext;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater mInflater = LayoutInflater.from(mcontext);
convertView = mInflater.inflate(R.layout.buju_order_collectionlist, null);
viewHolder.name = (TextView)convertView.findViewById(R.id.buju_order_collection_username);
viewHolder.date = (TextView)convertView.findViewById(R.id.buju_order_collection_time);
viewHolder.comment = (TextView)convertView.findViewById(R.id.buju_order_collection_text);
viewHolder.image = (ImageView)convertView.findViewById(R.id.buju_order_collection_pic);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.name.setText(data.get(position).get("name").toString());
viewHolder.date.setText(data.get(position).get("date").toString());
viewHolder.comment.setText(data.get(position).get("comment").toString());
Drawable bm = (Drawable)data.get(position).get("image");
viewHolder.image.setBackground(bm);
return convertView;
}
}
package net.codecode.consciencefood.fragment;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import net.codecode.consciencefood.DBOpenHelper;
import net.codecode.consciencefood.R;
import net.codecode.consciencefood.adapter.GourmetBaseAdapter;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
/**
* Created by shx and 2020/9/3.
*/
public class Gourmet_gragment extends Fragment {
private ListView mylistview;
private int images[] = {R.drawable.p1_gourmet, R.drawable.p2_gourmet,R.drawable.p3_gourmet,
R.drawable.p4_gourmet, R.drawable.p5_gourmet, R.drawable.p6_gourmet, R.drawable.p7_gourmet,
R.drawable.p8_gourmet};
private String[] comment = {"减肥干吗 又不是吃不起", "这样的馒头,感觉能吃一筐",
"给你一个能爱上烘焙的理由", "不是我瘦不下来 是敌人太强",
"一场咖啡与鲜花的比赛", "美食是灵魂伴侣",
"吃货的幸福世界", "美得舍不得下咽"};
private String[] name = {"叶德娴", "刘芸", "徐自贤", "丁志诚", "梁文道", "张笛", "杨若兮", "王丽达"};
private String[] date = {"2016年7月", "2016年9月", "2017年1月", "2017年2月", "2017年10月", "2018年5月", "2018年9月", "2018年10月"};
private List<HashMap> dataList;
GourmetBaseAdapter myBaseAdapter;
private DBOpenHelper openHelper;
@Override
public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View v, @Nullable ContextMenu.ContextMenuInfo menuInfo) {
menu.add(0, 1, Menu.NONE, "微信分享");
menu.add(0, 2, Menu.NONE, "收藏");
menu.add(0, 3, Menu.NONE, "删除");
super.onCreateContextMenu(menu, v, menuInfo);
}
public void dialog() {
AlertDialog.Builder mydialog = new AlertDialog.Builder(getActivity());
mydialog.setTitle("确认");
mydialog.setIcon(android.R.drawable.ic_dialog_alert);
mydialog.setMessage("您确认要在微信分享");
mydialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
@SuppressLint("WrongConstant")
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "你不微信分享了", 2000).show();
}
});
mydialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
@SuppressLint("WrongConstant")
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "微信分享成功", 2000).show();
}
});
mydialog.show();
}
@Override
@SuppressLint("WrongConstant")
public boolean onContextItemSelected(@NonNull MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
switch (item.getItemId()){
case 1:
dialog();
// Toast.makeText(getActivity(), "晚一点帮你分享", 2000).show();
break;
case 2:
// Toast.makeText(getActivity(), "晚一点帮你收藏", 2000).show();
collection(info.position);
break;
case 3:
dataList.remove(info.position);
myBaseAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private void collection(int selectindex) {
openHelper = new DBOpenHelper(this.getActivity(), "collection.db", null, 1);
SQLiteDatabase sqLiteDatabase = openHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", dataList.get(selectindex).get("name").toString());
values.put("date", dataList.get(selectindex).get("date").toString());
values.put("comment", dataList.get(selectindex).get("comment").toString());
values.put("image", getPicture(this.getResources().getDrawable((Integer)dataList.get(selectindex).get("image"))));
long i = sqLiteDatabase.insert("collection_imf", null, values);
if (i > -1) {
Toast.makeText(getActivity(), "亲,已收藏", Toast.LENGTH_LONG).show();
}
sqLiteDatabase.close();
}
private byte[] getPicture(Drawable drawable) {
if (drawable == null) {
return null;
}
BitmapDrawable bd = (BitmapDrawable)drawable;
Bitmap bitmap = bd.getBitmap();
ByteArrayOutputStream os = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
return os.toByteArray();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_gourmet, null);
initdata();
myBaseAdapter = new GourmetBaseAdapter(dataList, getActivity());
mylistview = (ListView)view.findViewById(R.id.gourment_frag_listView1);
mylistview.setAdapter(myBaseAdapter);
this.registerForContextMenu(mylistview);
return view;
}
private void initdata() {
dataList = new ArrayList();
for (int i = 0; i < date.length; i++) {
HashMap hm = new HashMap();
hm.put("image", images[i]);
hm.put("date", date[i]);
hm.put("comment", comment[i]);
hm.put("name", name[i]);
dataList.add(hm);
}
}
}
package net.codecode.consciencefood.fragment;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import net.codecode.consciencefood.R;
import net.codecode.consciencefood.adapter.HomeVpAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager.widget.ViewPager;
/**
* Created by shx and 2020/9/2.
*/
public class Home_fragment extends Fragment {
private ViewPager viewPager;
private List<ImageView> list_VP = new ArrayList<ImageView>();
private int[] image_VP = {R.drawable.guangao1, R.drawable.guangao2, R.drawable.guangao3};
TextView tv_radio;
LinearLayout ll_viewpager_don;
private List<TextView> tv_list = new ArrayList<TextView>();
private LinearLayout.LayoutParams layoutParams;
Thread mytr;
private String name_listview[] = {"新品驾到", "食趣", "食品安全", "产品溯源", "健康养生", "产品展示"};
private int image_listview[] = {R.drawable.no1, R.drawable.no2, R.drawable.no3, R.drawable.no4, R.drawable.no5, R.drawable.no6};
private GridView gridView;
private List list;
private Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
case 1:
viewPager.setCurrentItem((viewPager.getCurrentItem() + 1) % 3);
}
}
};
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_home, null);
initViewPager(view);
initGridView(view);
return view;
}
private void initGridView(View view) {
gridView = (GridView)view.findViewById(R.id.home_gridView1);
list = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < 6; i++) {
HashMap<String, Object> hmap = new HashMap<String, Object>();
hmap.put("name", name_listview[i]);
hmap.put("icon", image_listview[i]);
list.add(hmap);
}
SimpleAdapter adapter = new SimpleAdapter(getActivity(), list, R.layout.buju_home_gridview, new String[]{"name","icon"}, new int[]{R.id.buju_home_gridview_name, R.id.buju_home_gridview_icon});
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@SuppressLint("WrongConstant")
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
Toast.makeText(getActivity(), "新品驾到", 5000).show();
break;
case 1:
Toast.makeText(getActivity(), "食趣", 5000).show();
break;
case 2:
Toast.makeText(getActivity(), "食品安全", 5000).show();
break;
case 3:
Toast.makeText(getActivity(), "产品溯源", 5000).show();
break;
case 4:
Toast.makeText(getActivity(), "健康养身", 5000).show();
break;
case 5:
Toast.makeText(getActivity(), "产品展示", 5000).show();
break;
}
}
});
}
private void initViewPager(View view) {
viewPager = (ViewPager)view.findViewById(R.id.home_viewpager);
ll_viewpager_don = (LinearLayout)view.findViewById(R.id.home_viewpager_dot);
layoutParams = new LinearLayout.LayoutParams(20, 20);
layoutParams.setMargins(0,0,10,0);
for (int i = 0; i < image_VP.length; i++) {
ImageView imageV = new ImageView(getActivity());
imageV.setImageResource(image_VP[i]);
imageV.setAdjustViewBounds(true);
imageV.setScaleType(ImageView.ScaleType.FIT_XY);
list_VP.add(imageV);
tv_radio = new TextView(getActivity());
tv_radio.setBackgroundResource(R.drawable.tv_dot_selector);
ll_viewpager_don.addView(tv_radio, layoutParams);
tv_list.add(tv_radio);
}
viewPager.setAdapter(new HomeVpAdapter(list_VP));
viewPager.setCurrentItem(0);
tv_list.get(0).setSelected(true);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
for (int i = 0; i < tv_list.size(); i++) {
if (i == position % list_VP.size()) {
tv_list.get(i).setSelected(true);
} else {
tv_list.get(i).setSelected(false);
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void myThread() {
mytr = new Thread(new Runnable() {
@Override
public void run() {
while(!Thread.interrupted()) {
try {
Thread.sleep(5000);
handler.sendEmptyMessage(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
mytr.start();
}
@Override
public void onResume() {
myThread();
super.onResume();
}
@Override
public void onStop() {
mytr.interrupt();
super.onStop();
}
}
package net.codecode.consciencefood.fragment;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import net.codecode.consciencefood.DBOpenHelper;
import net.codecode.consciencefood.R;
import net.codecode.consciencefood.adapter.OrderBaseAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
/**
* Created by shx and 2020/9/4.
*/
public class Order_Fragment extends Fragment {
private int images[] = {R.drawable.po1_hetao, R.drawable.po2_mi, R.drawable.po3_jidan, R.drawable.po4_huasheng, R.drawable.po5_huajiao};
private String[] price = {"¥50 元公斤", "¥10 元公斤", "¥25 元公斤", "¥30 元公斤", "¥100 元公斤"};
private String[] address = {"云南大理", "惠州惠东", "惠州农门", "河源和平", "四川汶川"};
private String[] name = {"核桃", "大米", "鸡蛋", "花生", "花椒"};
ArrayList dataList;
ListView order;
private List collectionList;
private ListView collection;
private DBOpenHelper openHelper;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_order, null);
init(view);
showOrder();
showCollection();
return view;
}
private void showCollection() {
getCollection();
OrderBaseAdapter myadapter = new OrderBaseAdapter(collectionList, this.getActivity());
collection.setAdapter(myadapter);
}
private void getCollection() {
collectionList = new ArrayList();
openHelper = new DBOpenHelper(this.getActivity(), "collection.db", null, 1);
SQLiteDatabase sqliteDatabase = openHelper.getReadableDatabase();
Cursor cursor = sqliteDatabase.query("collection_imf", null, null, null, null, null, null);
if (cursor != null && cursor.getCount() != 0) {
while (cursor.moveToNext()) {
HashMap hm = new HashMap();
String name = cursor.getString(cursor.getColumnIndex("name"));
String date = cursor.getString(cursor.getColumnIndex("date"));
String comment = cursor.getString(cursor.getColumnIndex("comment"));
byte[] b = cursor.getBlob(cursor.getColumnIndex("image"));
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length,null);
Drawable drawable = new BitmapDrawable(bitmap);
hm.put("name", name);
hm.put("date", date);
hm.put("comment", comment);
hm.put("image", drawable);
collectionList.add(hm);
}
}
}
private void showOrder() {
initData();
SimpleAdapter adapter = new SimpleAdapter(this.getActivity(), dataList, R.layout.buju_order_orderlist,
new String[]{"image", "price", "address", "name"},
new int[] {R.id.buju_orderList_pic, R.id.buju_orderList_price, R.id.buju_orderList_address, R.id.buju_orderList_name});
order.setAdapter(adapter);
}
private void initData() {
dataList = new ArrayList();
for (int i = 0; i < images.length; i++) {
HashMap hm = new HashMap();
hm.put("image", images[i]);
hm.put("price", price[i]);
hm.put("address", address[i]);
hm.put("name", name[i]);
dataList.add(hm);
}
}
private void init(View view) {
order = (ListView)view.findViewById(R.id.frag_order_orderList);
collection = (ListView)view.findViewById(R.id.frag_order_collectionList);
}
}
package net.codecode.consciencefood.fragment;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import net.codecode.consciencefood.LocationActivity;
import net.codecode.consciencefood.LoginActivity;
import net.codecode.consciencefood.MoreActivity;
import net.codecode.consciencefood.R;
import net.codecode.consciencefood.util.PermissionUtil;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
/**
* Created by shx and 2020/8/28.
*/
public class PersonalCenter extends Fragment{
ImageView iv;
TextView moreTextView;
ImageView moreImageView;
View view = null;
TextView tvUsername;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.frag_personalcenter, null);
tvUsername = (TextView)view.findViewById(R.id.textView);
moreTextView = (TextView)view.findViewById(R.id.textView7);
moreTextView.setOnClickListener(new ClickMore());
moreImageView = (ImageView)view.findViewById(R.id.imageView7);
moreImageView.setOnClickListener(new ClickMore());
// 更多
iv = (ImageView)view.findViewById(R.id.nextimageView7);
iv.setOnClickListener(new ClickMore());
// iv.setOnClickListener(new View.OnClickListener(){
// @Override
// public void onClick(View v) {
// Intent it = new Intent(getActivity(), MoreActivity.class);
// startActivity(it);
// }
// });
jumplogin(view);
return view;
}
public class ClickMore implements View.OnClickListener {
@Override
public void onClick(View v) {
Intent it = new Intent(getActivity(), MoreActivity.class);
startActivity(it);
}
}
public void initUser(View v) {
SharedPreferences sp = getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
String name = sp.getString("username", "notsave");
Button btn = (Button)v.findViewById(R.id.btnLogin);
// TextView tvUsername = (TextView)v.findViewById(R.id.textView);
if(name != "notsave") {
tvUsername.setText(name);
btn.setText("注销");
} else {
btn.setText("登录");
tvUsername.setText("请登录");
}
}
@Override
public void onResume() {
initUser(view);
super.onResume();
}
public void jumplogin(View v) {
Button login = (Button)v.findViewById(R.id.btnLogin);
// TextView login = (TextView)v.findViewById(R.id.textView);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Button btn = (Button)view;
if (btn.getText() == "注销") {
SharedPreferences sp = getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("username", "notsave");
editor.commit();
btn.setText("登录");
tvUsername.setText("请登录");
} else if (btn.getText() == "登录") {
Intent it = new Intent(getActivity(), LoginActivity.class);
startActivity(it);
}
}
});
}
}
package net.codecode.consciencefood.util;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
/**
* Bitmap util.
* <p>从Uri直接读取图片流,避免路径转换的适配问题</p>
*/
public class BitmapUtil {
/**
* 读取一个缩放后的图片,限定图片大小,避免OOM
*
* @param uri 图片uri,支持“file://”、“content://”
* @param maxWidth 最大允许宽度
* @param maxHeight 最大允许高度
* @return 返回一个缩放后的Bitmap,失败则返回null
*/
public static Bitmap decodeUri(Context context, Uri uri, int maxWidth, int maxHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; //只读取图片尺寸
readBitmapScale(context, uri, options);
//计算实际缩放比例
int scale = 1;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if ((options.outWidth / scale > maxWidth &&
options.outWidth / scale > maxWidth * 1.4) ||
(options.outHeight / scale > maxHeight &&
options.outHeight / scale > maxHeight * 1.4)) {
scale++;
} else {
break;
}
}
options.inSampleSize = scale;
options.inJustDecodeBounds = false;//读取图片内容
options.inPreferredConfig = Bitmap.Config.RGB_565; //根据情况进行修改
Bitmap bitmap = null;
try {
bitmap = readBitmapData(context, uri, options);
} catch (Throwable e) {
e.printStackTrace();
}
return bitmap;
}
private static void readBitmapScale(Context context, Uri uri, BitmapFactory.Options options) {
if (uri == null) {
return;
}
String scheme = uri.getScheme();
if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||
ContentResolver.SCHEME_FILE.equals(scheme)) {
InputStream stream = null;
try {
stream = context.getContentResolver().openInputStream(uri);
BitmapFactory.decodeStream(stream, null, options);
} catch (Exception e) {
Log.w("readBitmapScale", "Unable to open content: " + uri, e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
Log.e("readBitmapScale", "Unable to close content: " + uri, e);
}
}
}
} else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
Log.e("readBitmapScale", "Unable to close content: " + uri);
} else {
Log.e("readBitmapScale", "Unable to close content: " + uri);
}
}
private static Bitmap readBitmapData(Context context, Uri uri, BitmapFactory.Options options) {
if (uri == null) {
return null;
}
Bitmap bitmap = null;
String scheme = uri.getScheme();
if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||
ContentResolver.SCHEME_FILE.equals(scheme)) {
InputStream stream = null;
try {
stream = context.getContentResolver().openInputStream(uri);
bitmap = BitmapFactory.decodeStream(stream, null, options);
} catch (Exception e) {
Log.e("readBitmapData", "Unable to open content: " + uri, e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
Log.e("readBitmapData", "Unable to close content: " + uri, e);
}
}
}
} else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
Log.e("readBitmapData", "Unable to close content: " + uri);
} else {
Log.e("readBitmapData", "Unable to close content: " + uri);
}
return bitmap;
}
}
\ No newline at end of file
package net.codecode.consciencefood.util;
import android.content.Context;
import android.graphics.Point;
import android.hardware.Camera;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import java.util.List;
import java.util.regex.Pattern;
public class CameraUtil {
private final static String TAG = "CameraUtil";
public static Point getSize(Context ctx) {
WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
Point size = new Point();
size.x = dm.widthPixels;
size.y = dm.heightPixels;
return size;
}
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
public static Point getCameraSize(Camera.Parameters params, Point screenSize) {
String previewSizeValueString = params.get("preview-size-values");
if (previewSizeValueString == null) {
previewSizeValueString = params.get("preview-size-value");
}
Point cameraSize = null;
if (previewSizeValueString != null) {
Log.d(TAG, "preview-size-values parameter: " + previewSizeValueString);
cameraSize = findBestPreviewSizeValue(previewSizeValueString, screenSize);
}
if (cameraSize == null) {
cameraSize = new Point((screenSize.x >> 3) << 3, (screenSize.y >> 3) << 3);
}
return cameraSize;
}
private static Point findBestPreviewSizeValue(CharSequence previewSizeValueString, Point screenSize) {
int bestX = 0;
int bestY = 0;
int diff = Integer.MAX_VALUE;
for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) {
previewSize = previewSize.trim();
int dimPosition = previewSize.indexOf('x');
if (dimPosition < 0) {
Log.d(TAG, "Bad preview-size: " + previewSize);
continue;
}
int newX;
int newY;
try {
newX = Integer.parseInt(previewSize.substring(0, dimPosition));
newY = Integer.parseInt(previewSize.substring(dimPosition + 1));
} catch (NumberFormatException nfe) {
Log.d(TAG, "Bad preview-size: " + previewSize);
continue;
}
int newDiff = Math.abs((newX - screenSize.x) + (newY - screenSize.y));
if (newDiff == 0) {
bestX = newX;
bestY = newY;
break;
} else if (newDiff < diff) {
bestX = newX;
bestY = newY;
diff = newDiff;
}
}
if (bestX > 0 && bestY > 0) {
return new Point(bestX, bestY);
}
return null;
}
public static Camera.Size getMaxPictureSize(Camera.Parameters params) {
List<Camera.Size> supportedSizes = params.getSupportedPictureSizes();
Camera.Size maxSize = supportedSizes.get(0);
for (Camera.Size size : supportedSizes) {
if (size.width > maxSize.width) {
maxSize = size;
}
}
return maxSize;
}
}
package net.codecode.consciencefood.util;
import android.annotation.SuppressLint;
import java.text.SimpleDateFormat;
import java.util.Date;
@SuppressLint("SimpleDateFormat")
public class DateUtil {
public static String getNowDateTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
return sdf.format(new Date());
}
public static String getNowDateTimeFull() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return sdf.format(new Date());
}
public static String getNowDateTimeFormat() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date());
}
public static String getNowTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
}
package net.codecode.consciencefood.util;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
/**
* Created by ouyangshen on 2018/1/28.
*/
public class PermissionUtil {
private final static String TAG = "PermissionUtil";
// 检查某个权限。返回true表示已启用该权限,返回false表示未启用该权限
public static boolean checkPermission(Activity act, String permission, int requestCode) {
Log.d(TAG, "checkPermission: "+permission);
boolean result = true;
// 只对Android6.0及以上系统进行校验
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// 检查当前App是否开启了名称为permission的权限
int check = ContextCompat.checkSelfPermission(act, permission);
if (check != PackageManager.PERMISSION_GRANTED) {
// 未开启该权限,则请求系统弹窗,好让用户选择是否立即开启权限
ActivityCompat.requestPermissions(act, new String[]{permission}, requestCode);
result = false;
}
}
return result;
}
// 检查多个权限。返回true表示已完全启用权限,返回false表示未完全启用权限
public static boolean checkMultiPermission(Activity act, String[] permissions, int requestCode) {
boolean result = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int check = PackageManager.PERMISSION_GRANTED;
// 通过权限数组检查是否都开启了这些权限
for (String permission : permissions) {
check = ContextCompat.checkSelfPermission(act, permission);
if (check != PackageManager.PERMISSION_GRANTED) {
break;
}
}
if (check != PackageManager.PERMISSION_GRANTED) {
// 未开启该权限,则请求系统弹窗,好让用户选择是否立即开启权限
ActivityCompat.requestPermissions(act, permissions, requestCode);
result = false;
}
}
return result;
}
public static void goActivity(Context ctx, Class<?> cls) {
Intent intent = new Intent(ctx, cls);
ctx.startActivity(intent);
}
}
package net.codecode.consciencefood.util;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import java.lang.reflect.Method;
import androidx.core.app.ActivityCompat;
@SuppressLint("WifiManagerPotentialLeak")
public class SwitchUtil {
private static final String TAG = "SwitchUtil";
// 获取定位功能的开关状态
public static boolean getGpsStatus(Context ctx) {
// 从系统服务中获取定位管理器
LocationManager lm = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
// 检查定位功能是否打开,若未打开则跳到系统的定位功能设置页面
public static void checkGpsIsOpen(Context ctx, String hint) {
if (!getGpsStatus(ctx)) {
Toast.makeText(ctx, hint, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
ctx.startActivity(intent);
}
}
// 获取无线网络的开关状态
public static boolean getWlanStatus(Context ctx) {
// 从系统服务中获取无线网络管理器
WifiManager wm = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
return wm.isWifiEnabled();
}
// 打开或关闭无线网络
public static void setWlanStatus(Context ctx, boolean enabled) {
// 从系统服务中获取无线网络管理器
WifiManager wm = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
wm.setWifiEnabled(enabled);
}
// // 检查是否插了sim卡
// public static boolean getSimcardStatus(Context ctx) {
// // 从系统服务中获取电话管理器
// TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
// if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
// return false;
// }
// String serial = tm.getSimSerialNumber();
// if (TextUtils.isEmpty(serial)) {
// return false;
// } else {
// return true;
// }
// }
// // 获取数据连接的开关状态
// public static boolean getMobileDataStatus(Context ctx) {
// // 如果没插sim卡,后面的getMobileDataEnabled也会返回true
// // 所以这里先判断一下有没有插卡,没插卡就表示无数据连接
// if (!getSimcardStatus(ctx)) {
// return false;
// }
// // 从系统服务中获取连接管理器
// ConnectivityManager cm = (ConnectivityManager)
// ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
// boolean isOpen = false;
// try {
// String methodName = "getMobileDataEnabled"; // 这是隐藏方法,需要通过反射调用
// Method method = cm.getClass().getMethod(methodName);
// isOpen = (Boolean) method.invoke(cm);
// Log.d(TAG, "getMobileDataStatus isOpen="+isOpen);
// } catch (Exception e) {
// e.printStackTrace();
// }
// return isOpen;
// }
// 打开或关闭数据连接
public static void setMobileDataStatus(Context ctx, boolean enabled) {
// 从系统服务中获取连接管理器
ConnectivityManager cm = (ConnectivityManager)
ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
String methodName = "setMobileDataEnabled"; // 这是隐藏方法,需要通过反射调用
Method method = cm.getClass().getMethod(methodName, Boolean.TYPE);
// method.setAccessible(true);
method.invoke(cm, enabled);
} catch (Exception e) {
e.printStackTrace();
}
}
// 设置亮度自动调节的开关
public static void setAutoBrightStatus(Context ctx, boolean enabled) {
int screenMode = (enabled) ? Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
: Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
Settings.System.putInt(ctx.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE, screenMode);
}
// 获取亮度自动调节的状态
public static boolean getAutoBrightStatus(Context ctx) {
int screenMode = Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
try {
screenMode = Settings.System.getInt(ctx.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE);
} catch (Exception e) {
e.printStackTrace();
}
return screenMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
}
// // Camera对象需要做成单例模式,因为Camera不能重复打开
// private static Camera mCamera = null;
//
// // 获取闪光灯/手电筒的开关状态
// public static boolean getFlashStatus(Context ctx) {
// if (mCamera == null) {
// mCamera = Camera.open();
// }
// Parameters parameters = mCamera.getParameters();
// String flashMode = parameters.getFlashMode();
// return flashMode.equals(Parameters.FLASH_MODE_TORCH);
// }
//
// // 打开或关闭闪光灯/手电筒
// public static void setFlashStatus(Context ctx, boolean enabled) {
// if (mCamera == null) {
// mCamera = Camera.open();
// }
// Parameters parameters = mCamera.getParameters();
// if (enabled) {
// parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);// 开启
// mCamera.setParameters(parameters);
// } else {
// parameters.setFlashMode(Parameters.FLASH_MODE_OFF);// 关闭
// mCamera.setParameters(parameters);
// mCamera.release();
// mCamera = null;
// }
// }
}
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
android:useLevel="false">
<solid android:color="@color/navigation_false"/>
<size android:width="10dp"
android:height="10dp"/>
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
android:useLevel="false">
<solid android:color="@color/public_green"/>
<size android:width="10dp"
android:height="10dp"/>
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="@dimen/edit_dimens"/>
<solid android:color="@color/edit_color"/>
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="@dimen/edit_dimens"></corners>
<solid android:color="@color/hint_textColor"/>
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@drawable/edit_login_shape_t"/>
<item android:state_focused="false" android:drawable="@drawable/edit_login_shape_f"/>
</selector>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<vector
android:height="108dp"
android:width="108dp"
android:viewportHeight="108"
android:viewportWidth="108"
xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z"/>
<path android:fillColor="#00000000" android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
</vector>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@drawable/don_true_shape"></item>
<item android:state_selected="false" android:drawable="@drawable/don_false_shape"></item>
</selector>
\ No newline at end of file
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/toolbar_scanner" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="@+id/sv_scan"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
<net.app.zxing.view.ViewfinderView
android:id="@+id/vv_finder"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!--<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="@drawable/bg_alpha"
android:gravity="center"
android:text="二维码扫描/条形码扫描"
android:textColor="@color/white"
android:textSize="20sp" />-->
</FrameLayout>
</LinearLayout>
\ No newline at end of file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="@+id/tv_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:textSize="17sp" />
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
\ No newline at end of file
<?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:layout_height="match_parent"
android:background="@drawable/login_bg"
android:orientation="vertical"
tools:context=".LoginActivity">
<!--android:background="@drawable/login_bg" -->
<ImageButton
android:id="@+id/close_login"
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:scaleType="centerCrop"
android:background="?attr/selectableItemBackground"
android:src="@drawable/close"/>
<TextView
android:id="@+id/Login_textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/login_title"
android:layout_marginLeft="30dp"
android:layout_marginTop="160dp"
android:textColor="@color/font_color"
android:textSize="@dimen/login_textsize" />
<EditText
android:id="@+id/Login_editUsername"
style="@style/login_et"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="@string/username"
android:drawableLeft="@mipmap/user"
android:inputType="textPersonName" />
<EditText
android:id="@+id/Login_editPassword"
style="@style/login_et"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="@string/password"
android:drawableLeft="@mipmap/pass"
android:inputType="textPassword" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="10dp">
<TextView
android:id="@+id/Login_nouser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="@string/forgetpsw"
android:textColor="@color/font_color"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.316"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintVertical_bias="0.51"/>
<Button
android:id="@+id/Login_btnLoginup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
style="@style/login_et"
android:text="登录"
android:textColor="@color/font_color"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.916"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintVertical_bias="0.523"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom|center_horizontal"
android:orientation="horizontal"
android:paddingBottom="35dp">
<TextView
android:id="@+id/Login_noUserTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/nouser"
android:textColor="@color/font_color"/>
<TextView
android:id="@+id/Login_regTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/reg"
android:textColor="@color/font_color"/>
</LinearLayout>
</LinearLayout>
<?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:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/public_green"
android:gravity="center"
android:text="@string/app_name"
android:textColor="#ffffff"
android:textSize="25sp"
android:textStyle="bold"/>
<FrameLayout
android:id="@+id/main_framelayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="10">
</FrameLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#eceae9"/>
<RadioGroup
android:id="@+id/main_radioGroup"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.5"
android:gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="@+id/main_radio0"
style="@style/main_RadioButton"
android:checked="true"
android:drawableTop="@mipmap/icon_home_true"
android:textColor="@color/public_green"
android:text="首页"/>
<RadioButton
android:id="@+id/main_radio1"
style="@style/main_RadioButton"
android:checked="true"
android:drawableTop="@mipmap/icon_community_false"
android:textColor="@color/navigation_false"
android:text="吃货驾到"/>
<RadioButton
android:id="@+id/main_radio2"
style="@style/main_RadioButton"
android:checked="true"
android:drawableTop="@mipmap/icon_order_false"
android:textColor="@color/navigation_false"
android:text="我的订单"/>
<RadioButton
android:id="@+id/main_radio3"
style="@style/main_RadioButton"
android:checked="true"
android:drawableTop="@mipmap/icon_me_false"
android:textColor="@color/navigation_false"
android:text="个人中心"/>
<RadioButton
android:id="@+id/main_radio4"
style="@style/main_RadioButton"
android:checked="true"
android:drawableTop="@mipmap/icon_me_false"
android:textColor="@color/navigation_false"
android:visibility="gone"
android:text="test"/>
</RadioGroup>
</LinearLayout>
\ No newline at end of file
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
style="@style/personal_Liner"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView1"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_weight="1"
android:src="@mipmap/weather"/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="天气"/>
<ImageView
android:id="@+id/weatherdetail"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_weight="1"
android:src="@mipmap/next"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
style="@style/personal_Liner"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView2"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_weight="1"
android:src="@mipmap/position"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="位置"/>
<ImageView
android:id="@+id/positiondetail"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_weight="1"
android:src="@mipmap/next"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
style="@style/personal_Liner"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView3"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_weight="1"
android:src="@mipmap/scan"/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="扫一扫"/>
<ImageView
android:id="@+id/scandetail"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_weight="1"
android:src="@mipmap/next"/>
</LinearLayout>
</LinearLayout>
\ No newline at end of file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="@+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:textSize="17sp" />
</LinearLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:minHeight="100dp">
<ImageView
android:id="@+id/buju_gourment_pic"
android:layout_width="100dp"
android:layout_height="80dp"
android:layout_marginTop="10dp"
android:paddingLeft="30dp"
android:scaleType="fitStart"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:orientation="vertical">
<TextView
android:id="@+id/buju_gourment_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:maxLines="5"
android:text="内容"
android:textColor="#000"/>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<TextView
android:id="@+id/buju_gourment_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户名"
android:textColor="#60000000"
android:textSize="12sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/buju_goument_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:text="时间"
android:textColor="#60000000"
android:textSize="12sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toRightOf="@id/buju_gourment_username"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<ImageView
android:id="@+id/buju_goument_praise"
android:layout_width="15dp"
android:layout_height="15dp"
android:src="@drawable/thumb_up"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/buju_gourment_count"
android:layout_width="8dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:text="0"
android:textColor="#60000000"
app:layout_constraintStart_toStartOf="@id/buju_goument_praise"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/one_buju_relativelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/buju_home_gridview_icon"
android:layout_width="50dp"
android:layout_height="50dp"/>
<TextView
android:id="@+id/buju_home_gridview_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textColor="#999999"
android:textSize="13sp"/>
</LinearLayout>
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:minHeight="100dp">
<ImageView
android:id="@+id/buju_order_collection_pic"
android:layout_width="100dp"
android:layout_height="80dp"
android:layout_marginTop="10dp"
android:paddingLeft="30dp"
android:scaleType="fitStart"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:orientation="vertical">
<TextView
android:id="@+id/buju_order_collection_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:maxLines="5"
android:text="内容"
android:textColor="#000"/>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<TextView
android:id="@+id/buju_order_collection_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户名"
android:textColor="#60000000"
android:textSize="12sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/buju_order_collection_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:text="时间"
android:textColor="#60000000"
android:textSize="12sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toRightOf="@id/buju_order_collection_username"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/buju_orderList_pic"
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_marginTop="10dp"
android:paddingLeft="30dp"
android:scaleType="fitStart"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:layout_marginLeft="10dp"
android:orientation="vertical">
<TextView
android:id="@+id/buju_orderList_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:text="产品名"/>
<TextView
android:id="@+id/buju_orderList_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="10sp"
android:textColor="#D1D1D1"
android:text="产地"/>
<TextView
android:id="@+id/buju_orderList_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="10sp"
android:textColor="#D1D1D1"
android:text="价格"/>
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/gourment_frag_listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#EAEAEA"
android:dividerHeight="2dp"
android:listSelector="#EAEAEA"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:id="@+id/home_viewpager"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="5dp">
</androidx.viewpager.widget.ViewPager>
<LinearLayout
android:id="@+id/home_viewpager_dot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:gravity="center"
android:orientation="horizontal"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
</LinearLayout>
<GridView
android:id="@+id/home_gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="#ffffff"
android:cacheColorHint="#00000000"
android:horizontalSpacing="1dp"
android:verticalSpacing="10dp"
android:listSelector="#fff"
android:numColumns="3"
android:paddingBottom="5dp"
android:paddingTop="5dp"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/frag_order_textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="最近订单"/>
<ListView
android:id="@+id/frag_order_orderList"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:layout_marginTop="10dp"
android:orientation="vertical">
<TextView
android:id="@+id/frag_order_textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="我的收藏"/>
<ListView
android:id="@+id/frag_order_collectionList"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</LinearLayout>
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<ImageView
android:id="@+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_margin="8dp"
android:src="@mipmap/login_userpic1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintHorizontal_bias="0.025" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:text="请登录"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/imageView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.512"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/personal_Liner"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@mipmap/personalinfo"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="个人信息"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/personal_Liner"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@mipmap/modifypwd"/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="修改密码"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/personal_Liner"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@mipmap/collection"/>
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="我的收藏"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/personal_Liner"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@mipmap/foodie"/>
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="我是吃货"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
style="@style/personal_Liner"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@mipmap/setting"/>
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="设置"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
style="@style/personal_Liner"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView7"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_weight="1"
android:src="@mipmap/more"/>
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="更多"/>
<ImageView
android:id="@+id/nextimageView7"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_weight="1"
android:src="@mipmap/next"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
style="@style/personal_Liner"
android:orientation="horizontal">
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textStyle="bold"
android:layout_marginLeft="150dp"
android:padding="3dp"
android:text="登录" />
</LinearLayout>
</LinearLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/gpsLocationItem"
android:orientation="horizontal">
<TextView
android:id="@+id/longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="经度:"/>
<TextView
android:id="@+id/longitude_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="longitude"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/weatherItem"
android:orientation="horizontal">
<TextView
android:id="@+id/latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="纬度:"/>
<TextView
android:id="@+id/latitude_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="latitude"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/weatherItem"
android:orientation="horizontal">
<TextView
android:id="@+id/altitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="高度:"/>
<TextView
android:id="@+id/altitude_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="altitude"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/weatherItem"
android:orientation="horizontal">
<TextView
android:id="@+id/accuracy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="精度:"/>
<TextView
android:id="@+id/accuracy_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="accuracy"/>
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:contentInsetStart="0dip">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<ImageButton
android:id="@+id/btn_back"
android:layout_width="40dip"
android:layout_height="40dip"
android:layout_centerVertical="true"
android:background="?attr/selectableItemBackground"
android:padding="10dip"
android:scaleType="centerCrop"
android:src="@drawable/btn_back" />
<TextView
android:id="@+id/txt_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="扫描二维码"
android:textColor="@android:color/white"
android:textSize="18sp" />
<Button
android:id="@+id/btn_album"
android:layout_width="40dip"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dip"
android:background="?attr/selectableItemBackground"
android:text="相册"
android:textColor="@android:color/white" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/weatherItem"
android:orientation="horizontal">
<TextView
android:id="@+id/city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="城市:"/>
<TextView
android:id="@+id/cityValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="city"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/weatherItem"
android:orientation="horizontal">
<TextView
android:id="@+id/lowest_temperature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="最低温度:"/>
<TextView
android:id="@+id/lowest_temperature_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="tem2"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/weatherItem"
android:orientation="horizontal">
<TextView
android:id="@+id/highest_temperature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="最高温度:"/>
<TextView
android:id="@+id/highest_temperature_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="tem2"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/weatherItem"
android:orientation="horizontal">
<TextView
android:id="@+id/win"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="风向:"/>
<TextView
android:id="@+id/win_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="win"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/weatherItem"
android:orientation="horizontal">
<TextView
android:id="@+id/wea"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="天气:"/>
<TextView
android:id="@+id/wea_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="weather"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/weatherItem"
android:orientation="horizontal">
<TextView
android:id="@+id/air_level"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="空气质量:"/>
<TextView
android:id="@+id/air_level_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="air_level"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/weatherItem"
android:orientation="horizontal">
<TextView
android:id="@+id/pm25"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="pm2.5:"/>
<TextView
android:id="@+id/pm25_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="pm2.5"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/weatherItem"
android:orientation="horizontal">
<TextView
android:id="@+id/visibility"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="能见度:"/>
<TextView
android:id="@+id/visibility_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="visibility"/>
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="edit_color">#40ffffff</color>
<color name="hint_textColor">#60000000</color>
<color name="font_color">#000000</color>
<color name="black">#000000</color>
<color name="blue">#0000ff</color>
<color name="public_green">#468500</color>
<color name="navigation_false">#60000000</color>
<color name="white">#ffffff</color>
<color name="login_font_color">#c0ffff00</color>
<color name="possible_result_points">#c0ffff00</color>
<color name="result_points">#c000ff00</color>
<color name="result_view">#b0000000</color>
<color name="viewfinder_frame">#ff000000</color>
<color name="viewfinder_laser">#ffff0000</color>
<color name="viewfinder_mask">#60000000</color>
</resources>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="login_textsize">30sp</dimen>
<dimen name="edit_dimens">10dp</dimen>
<dimen name="Navigation_RadioButtonsize">10sp</dimen>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Messages IDs -->
<item type="id" name="auto_focus"/>
<item type="id" name="decode"/>
<item type="id" name="decode_failed"/>
<item type="id" name="decode_succeeded"/>
<item type="id" name="encode_failed"/>
<item type="id" name="encode_succeeded"/>
<item type="id" name="launch_product_query"/>
<item type="id" name="quit"/>
<item type="id" name="restart_preview"/>
<item type="id" name="return_scan_result"/>
</resources>
\ No newline at end of file
<resources>
<string name="app_name">良心食品</string>
<string name="login_title">登入</string>
<string name="username">手机号/邮箱</string>
<string name="password">&#160;</string>
<string name="forgetpsw">忘记密码?点击找回</string>
<string name="nouser">还没有帐号?</string>
<string name="reg">注册</string>
<string name="scan_text">将二维码/条形码放入框内, 即可自动扫描</string>
</resources>
\ No newline at end of file
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<!-- <item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item> -->
</style>
<style name="login_et">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">45dp</item>
<item name="android:textColor">#ffffff</item>
<item name="android:background">@drawable/edituser_selector</item>
<item name="android:layout_marginLeft">30dp</item>
<item name="android:layout_marginRight">30dp</item>
<item name="android:maxLength">20</item>
<item name="android:textColorHint">@color/hint_textColor</item>
<item name="android:textSize">@dimen/login_textsize</item>
<item name="android:layout_gravity">center_horizontal</item>
<item name="android:drawablePadding">8dp</item>
<item name="android:singleLine">true</item>
</style>
<style name="main_RadioButton">
<item name="android:layout_height">match_parent</item>
<item name="android:layout_width">0dp</item>
<item name="android:layout_marginTop">4dp</item>
<item name="android:layout_weight">1</item>
<item name="android:button">@null</item>
<item name="android:drawablePadding">5dp</item>
<item name="android:gravity">center_horizontal</item>
<item name="android:textColor">@color/public_green</item>
<item name="android:textSize">@dimen/Navigation_RadioButtonsize</item>
</style>
<style name="personal_Liner">
<item name="android:background">#fff</item>
<item name="android:layout_marginBottom">2dp</item>
<item name="android:padding">5dp</item>
<item name="android:gravity">center_vertical</item>
</style>
<style name="weatherItem">
<item name="android:background">#fff</item>
<item name="android:layout_marginBottom">2dp</item>
<item name="android:padding">5dp</item>
<item name="android:gravity">center_vertical</item>
</style>
<style name="gpsLocationItem">
<item name="android:background">#fff</item>
<item name="android:layout_marginBottom">2dp</item>
<item name="android:padding">5dp</item>
<item name="android:gravity">center_vertical</item>
</style>
</resources>
\ No newline at end of file
package net.codecode.consciencefood;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
\ No newline at end of file
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.3.72"
ext.navigationVersion = '2.2.0-rc02'
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$navigationVersion"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
ext {
espressoVersion = '3.2.0'
}
\ No newline at end of file
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
\ No newline at end of file
#Wed Aug 26 13:14:47 GMT+08:00 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6-all.zip
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
include ':app'
rootProject.name = "ConsciencefoodThird"
\ No newline at end of file
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论