提交 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.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;
/**
* 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);
}
}
});
}
}
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论